代码高亮测试文档

用于测试各语言代码块的语法高亮效果。


Bash

 1#!/bin/bash
 2
 3# 定义变量
 4NAME="World"
 5COUNT=5
 6
 7# 循环输出
 8for i in $(seq 1 $COUNT); do
 9    echo "Hello, $NAME! 第 $i 次"
10done
11
12# 函数定义
13greet() {
14    local user=$1
15    if [ -z "$user" ]; then
16        echo "用法: greet <用户名>"
17        return 1
18    fi
19    echo "你好, $user!"
20}
21
22greet "Claude"
23
24# 文件操作
25if [ -f "/etc/os-release" ]; then
26    source /etc/os-release
27    echo "当前系统: $NAME $VERSION_ID"
28fi

CSS

 1/* 全局样式重置 */
 2:root {
 3    --primary-color: #3498db;
 4    --font-size-base: 16px;
 5}
 6
 7body {
 8    margin: 0;
 9    padding: 0;
10    font-family: 'Segoe UI', sans-serif;
11    font-size: var(--font-size-base);
12    background-color: #f5f5f5;
13}
14
15/* 卡片组件 */
16.card {
17    display: flex;
18    flex-direction: column;
19    align-items: center;
20    width: 300px;
21    padding: 1.5rem;
22    border-radius: 8px;
23    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
24    transition: transform 0.3s ease;
25}
26
27.card:hover {
28    transform: translateY(-4px);
29}
30
31@media (max-width: 768px) {
32    .card {
33        width: 100%;
34    }
35}

JavaScript

 1// 异步数据获取示例
 2const API_URL = "https://api.example.com";
 3
 4// 封装 fetch 请求
 5async function fetchData(endpoint) {
 6    try {
 7        const response = await fetch(`${API_URL}/${endpoint}`);
 8        if (!response.ok) throw new Error(`HTTP 错误: ${response.status}`);
 9        return await response.json();
10    } catch (err) {
11        console.error("请求失败:", err.message);
12        return null;
13    }
14}
15
16// 使用 Promise 链
17fetchData("users")
18    .then(data => data?.map(user => ({ id: user.id, name: user.name })))
19    .then(users => console.log("用户列表:", users))
20    .catch(console.error);
21
22// 防抖函数
23function debounce(fn, delay = 300) {
24    let timer;
25    return (...args) => {
26        clearTimeout(timer);
27        timer = setTimeout(() => fn(...args), delay);
28    };
29}
30
31const handleSearch = debounce(query => console.log("搜索:", query));

Java

 1import java.util.List;
 2import java.util.stream.Collectors;
 3
 4// 泛型栈实现
 5public class Stack<T> {
 6    private final List<T> items = new java.util.ArrayList<>();
 7
 8    public void push(T item) {
 9        items.add(item);
10    }
11
12    public T pop() {
13        if (isEmpty()) throw new RuntimeException("栈为空");
14        return items.remove(items.size() - 1);
15    }
16
17    public boolean isEmpty() {
18        return items.isEmpty();
19    }
20
21    // Stream 操作示例
22    public static void main(String[] args) {
23        List<String> names = List.of("Alice", "Bob", "Charlie", "Dave");
24
25        String result = names.stream()
26            .filter(name -> name.length() > 3)
27            .map(String::toUpperCase)
28            .collect(Collectors.joining(", "));
29
30        System.out.println("过滤结果: " + result);
31    }
32}

C

 1#include <stdio.h>
 2#include <stdlib.h>
 3#include <string.h>
 4
 5/* 链表节点定义 */
 6typedef struct Node {
 7    int data;
 8    struct Node *next;
 9} Node;
10
11/* 创建新节点 */
12Node *create_node(int data) {
13    Node *node = (Node *)malloc(sizeof(Node));
14    if (!node) {
15        fprintf(stderr, "内存分配失败\n");
16        exit(EXIT_FAILURE);
17    }
18    node->data = data;
19    node->next = NULL;
20    return node;
21}
22
23/* 打印链表 */
24void print_list(Node *head) {
25    for (Node *cur = head; cur != NULL; cur = cur->next) {
26        printf("%d -> ", cur->data);
27    }
28    printf("NULL\n");
29}
30
31int main() {
32    Node *head = create_node(1);
33    head->next = create_node(2);
34    head->next->next = create_node(3);
35    print_list(head);
36    return 0;
37}

C++

 1#include <iostream>
 2#include <vector>
 3#include <algorithm>
 4
 5// 模板函数:快速排序
 6template <typename T>
 7void quick_sort(std::vector<T>& arr, int left, int right) {
 8    if (left >= right) return;
 9    T pivot = arr[(left + right) / 2];
10    int i = left, j = right;
11
12    while (i <= j) {
13        while (arr[i] < pivot) i++;
14        while (arr[j] > pivot) j--;
15        if (i <= j) std::swap(arr[i++], arr[j--]);
16    }
17
18    quick_sort(arr, left, j);
19    quick_sort(arr, i, right);
20}
21
22int main() {
23    std::vector<int> nums = {5, 3, 8, 1, 9, 2, 7};
24    quick_sort(nums, 0, nums.size() - 1);
25
26    std::cout << "排序结果: ";
27    for (const auto& n : nums) std::cout << n << " ";
28    std::cout << std::endl;
29
30    return 0;
31}

PHP

 1<?php
 2
 3// 数据库连接类(PDO 封装)
 4class Database {
 5    private PDO $pdo;
 6
 7    public function __construct(string $dsn, string $user, string $pass) {
 8        $this->pdo = new PDO($dsn, $user, $pass, [
 9            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
10            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
11        ]);
12    }
13
14    // 安全查询
15    public function query(string $sql, array $params = []): array {
16        $stmt = $this->pdo->prepare($sql);
17        $stmt->execute($params);
18        return $stmt->fetchAll();
19    }
20}
21
22// 路由分发示例
23$routes = [
24    'GET /users'    => fn() => ['status' => 'ok', 'data' => []],
25    'POST /users'   => fn() => ['status' => 'created'],
26];
27
28$method = $_SERVER['REQUEST_METHOD'];
29$path   = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
30$key    = "$method $path";
31
32$response = isset($routes[$key]) ? $routes[$key]() : ['status' => 404];
33echo json_encode($response);

Rust

 1use std::collections::HashMap;
 2
 3// 枚举定义
 4#[derive(Debug)]
 5enum Shape {
 6    Circle(f64),
 7    Rectangle(f64, f64),
 8    Triangle(f64, f64, f64),
 9}
10
11impl Shape {
12    // 计算面积
13    fn area(&self) -> f64 {
14        match self {
15            Shape::Circle(r)         => std::f64::consts::PI * r * r,
16            Shape::Rectangle(w, h)   => w * h,
17            Shape::Triangle(a, b, c) => {
18                let s = (a + b + c) / 2.0;
19                (s * (s - a) * (s - b) * (s - c)).sqrt()
20            }
21        }
22    }
23}
24
25fn main() {
26    let shapes: Vec<Shape> = vec![
27        Shape::Circle(5.0),
28        Shape::Rectangle(4.0, 6.0),
29        Shape::Triangle(3.0, 4.0, 5.0),
30    ];
31
32    for shape in &shapes {
33        println!("{:?} 面积: {:.2}", shape, shape.area());
34    }
35
36    // HashMap 统计词频
37    let text = "hello world hello rust world hello";
38    let mut freq: HashMap<&str, u32> = HashMap::new();
39    for word in text.split_whitespace() {
40        *freq.entry(word).or_insert(0) += 1;
41    }
42    println!("词频统计: {:?}", freq);
43}

Python

 1from dataclasses import dataclass, field
 2from typing import Optional
 3import functools
 4
 5# 数据类定义
 6@dataclass
 7class Student:
 8    name: str
 9    score: float
10    grade: str = field(init=False)
11
12    def __post_init__(self):
13        self.grade = self._calc_grade()
14
15    def _calc_grade(self) -> str:
16        match self.score:
17            case s if s >= 90: return "A"
18            case s if s >= 75: return "B"
19            case s if s >= 60: return "C"
20            case _:            return "F"
21
22# 装饰器:缓存计算结果
23@functools.lru_cache(maxsize=128)
24def fibonacci(n: int) -> int:
25    """递归计算斐波那契数列(带缓存)"""
26    if n < 2:
27        return n
28    return fibonacci(n - 1) + fibonacci(n - 2)
29
30# 生成器:无限素数序列
31def primes():
32    sieve: dict[int, int] = {}
33    n = 2
34    while True:
35        if n not in sieve:
36            yield n
37            sieve[n * n] = n
38        else:
39            p = sieve.pop(n)
40            sieve[n + p] = p
41        n += 1
42
43if __name__ == "__main__":
44    students = [Student("Alice", 92), Student("Bob", 78), Student("Carol", 55)]
45    for s in sorted(students, key=lambda x: -x.score):
46        print(f"{s.name}: {s.score} ({s.grade})")
47
48    gen = primes()
49    print("前10个素数:", [next(gen) for _ in range(10)])

文档结束 — 共 9 种语言