代码片段仓库

收集、管理和分享有用的代码片段,提高开发效率

代码片段

Java异步 Java

CompletableFuture示例

import java.util.concurrent.*;

public class AsyncDemo {
    public static void main(String[] args) {
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("Async task completed");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        });
        
        future.thenAccept(
            result -> System.out.println("Callback executed")
        );
        
        System.out.println("Main thread continues");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {}
    }
}
C++模板 C++

编译时阶乘计算

#include <iostream>

template <int N>
struct Factorial {
    enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<1> {
    enum { value = 1 };
};

int main() {
    std::cout << "Factorial of 5: " << Factorial<5>::value << std::endl;
    return 0;
}
SQL递归CTE SQL

组织层级查询

WITH RECURSIVE EmployeeCTE (ID, Name, ManagerID, HierarchyLevel) AS (
    SELECT ID, Name, ManagerID, 0 AS HierarchyLevel
    FROM Employees
    WHERE ManagerID IS NULL
    
    UNION ALL
    
    SELECT e.ID, e.Name, e.ManagerID, HierarchyLevel + 1
    FROM Employees AS e
    JOIN EmployeeCTE ON e.ManagerID = EmployeeCTE.ID
)
SELECT * FROM EmployeeCTE;
TS泛型 TypeScript

通用响应类型

interface ApiResponse<T> {
  data: T;
  error?: string;
  status: number;
}

function createResponse<T>(
  data: T, 
  error?: string,
  status: number
): ApiResponse<T> {
  return { data, error, status };
}

let userResponse: ApiResponse<{name: string}> = createResponse({ name: 'John' });
Python数据类 Python

使用dataclass

from dataclasses import dataclass

dataclass
class Point:
    x: float
    y: float
   
    def distance(self, other: 'Point') -> float:
        return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5

p1 = Point(1.0, 2.0)
p2 = Point(3.0, 4.0)
dist = p1.distance(p2)
print(f"Distance: {dist}")
PostgreSQL JSON SQL

JSON数据查询

CREATE TABLE products (
  id SERIAL PRIMARY KEY,
  data JSONB NOT NULL
);

INSERT INTO products (data) VALUES
  ({"name": "Laptop", "price": 999.99, "attributes": {"color": "silver", "ram": 16}});

SELECT
  data->&name' AS name,
  (data->'0price')::numeric AS price,
  data->'attributes'OGt'color' AS color
FROM products;

为什么选择CodeSnippets?

高效管理您的代码片段,提高开发效率

智能搜索

通过关键字、语言或分类快速查找代码片段,支持模糊搜索和过滤功能

语法高亮

支持多种编程语言的语法高亮,使代码更加清晰易读

多设备同步

随时随地访问您的代码片段库,支持桌面和移动设备

热门分类

浏览最受欢迎的代码分类