跳转到内容

附录 E 跨语言对照表

这张表给在几种语言之间来回切换的人:一行一个常用概念,Python、JS/TS、C#、Go 四列并排,每格只放一种最常用的写法,压成一行。完整的可运行代码、同一概念的其他写法和注意事项在附录 A 到 D 的同名小节里,表里的写法和速查表一致。JS/TS 一列里标“TS”的写法只有 TypeScript 才有;语言没有这个特性时写“没有”,括号里是讲原因的正文章节,后面跟常用的替代写法。省略号表示省掉的代码。

概念 Python JS/TS C# Go
运行单个文件 python hello.py node hello.js dotnet run app.cs go run main.go
概念 Python JS/TS C# Go
定义变量 count = 0 let count = 0; var name = "Ada"; name := "Ada"
常量 MAX_RETRIES = 3(只是命名约定) const name = "Ada"; const int MaxRetries = 3; const timeout = 5
交换两个变量 a, b = b, a [a, b] = [b, a]; (a, b) = (b, a); x, y = y, x
概念 Python JS/TS C# Go
字符串转整数 int("42") Number("42") int.Parse("42") n, err := strconv.Atoi("42")
概念 Python JS/TS C# Go
字符串插值 f"{name} 今年 {age} 岁" `${name} 今年 ${age} 岁` $"{name} 今年 {age} 岁" 没有插值语法,用 fmt.Sprintf("%s 今年 %d 岁", name, age)
多行字符串 """…""" `…`(模板字符串里直接换行) """…"""(原始字符串字面量) `…`(反引号)
字符串长度 len(s)(码点数) s.length(UTF-16 码元数) s.Length(UTF-16 码元数) len(s)(UTF-8 字节数)
概念 Python JS/TS C# Go
列表字面量 nums = [3, 1, 2] const nums = [3, 1, 2]; List<int> nums = [3, 1, 2]; nums := []int{3, 1, 2}
字典字面量 {"小明": 18, "小红": 20} new Map([["小明", 18], ["小红", 20]]) new Dictionary<string, int> { ["小明"] = 18, ["小红"] = 20 } map[string]int{"小明": 18, "小红": 20}
列表推导或等价写法 [n * n for n in nums if n % 2 == 0] nums.filter((n) => n % 2 === 0).map((n) => n * n) nums.Where(n => n % 2 == 0).Select(n => n * n).ToList() 没有(第 13 章),用 for 循环加 append
排序 sorted(words, key=str.lower)(返回新列表) nums.toSorted((a, b) => a - b)(返回新数组) nums.Sort();(原地排序) slices.Sort(nums)(原地排序)
概念 Python JS/TS C# Go
if 表达式 "奇数" if n % 2 else "偶数" n % 2 ? "奇数" : "偶数" n % 2 == 1 ? "奇数" : "偶数" 没有(第 1 章),用 if/else 语句
遍历带下标 for i, ch in enumerate("ab", start=1): for (const [i, ch] of ["a", "b"].entries()) foreach (var (i, s) in letters.Index()) for i, s := range []string{"a", "b"}
switch/match match code: case 200 | 201: … switch (code) { case 404: …; break; } score switch { >= 90 => "A", >= 80 => "B", _ => "C" } switch code { case 200, 201: … }
概念 Python JS/TS C# Go
定义函数 def add(a: int, b: int) -> int: function add(a, b) { return a + b; } public static int Add(int a, int b) => a + b; func add(a, b int) int { return a + b }
默认参数 def greet(name: str, greeting: str = "你好") -> str: function greet(name, greeting = "你好") string Greet(string name, string greeting = "你好") => … 没有(第 7 章),用选项结构体 GreetOptions{Greeting: "早上好"}
匿名函数 lambda x: x * 2 (x) => x * 2 x => x * 2 func(x int) int { return x * 2 }
多返回值 lo, hi = min_max([3, 1, 4]) const [lo, hi] = minMax([3, 1, 4]); var (lo, hi) = MinMax([3, 1, 4]); q, err := divide(7, 2)
概念 Python JS/TS C# Go
定义类或结构 class Account:,构造方法 def __init__(self, owner: str, …) class Account { constructor(owner) { this.owner = owner; } } class Account(string owner) { … } type User struct { Name string; Age int }
继承 class Dog(Animal): class Dog extends Animal sealed class Dog(string name) : Animal(name) 没有(第 8 章),用嵌入 type Dog struct { Animal; Breed string }
概念 Python JS/TS C# Go
定义接口 class Shape(Protocol): def area(self) -> float: ... TS interface Shape { area(): number; };JS 没有(第 8 章),靠鸭子类型 interface IShape { double Area(); } type Shape interface { Area() float64 }
概念 Python JS/TS C# Go
泛型函数 def first[T](items: list[T]) -> T: TS function first<T>(items: T[]): T | undefined;JS 没有(第 9 章) T First<T>(IReadOnlyList<T> items) => items[0]; func Map[T, U any](items []T, f func(T) U) []U
概念 Python JS/TS C# Go
抛出错误 raise ValueError(f"负数不能开平方:{x}") throw new Error("网络断了"); throw new InvalidOperationException("网络断了"); 没有异常(第 10 章),返回 errors.New("除数为零")
捕获错误 try: … except ValueError as e: … try { … } catch (e) { … } try { … } catch (FormatException e) { … } if err != nil { … }
资源清理 with open("demo.txt", encoding="utf-8") as f: try { … } finally { await file.close(); } using var section = new Section("求和"); defer f.Close()
概念 Python JS/TS C# Go
空值判断 result is None v == null(同时判断 null 和 undefined) nickname is null p == nil
安全访问 没有(第 6 章),用 len(name) if name is not None else 0 user.profile?.name user.Profile?.Name 没有(第 6 章),用 if u.Profile != nil { … }
空值时取默认值 count if count is not None else 10 count ?? 10 input ?? "默认" 没有 ??(第 6 章),用 cmp.Or(input, "默认")
概念 Python JS/TS C# Go
导入 from pathlib import Path import { readFileSync } from "node:fs"; using System.Text; import "fmt"
概念 Python JS/TS C# Go
生成器或迭代器 def fib(): … yield a function* fib() { … yield a; } IEnumerable<int> Fib() { … yield return a; } 没有生成器(第 13 章),返回 iter.Seq[int],在里面调用 yield(i)
概念 Python JS/TS C# Go
启动并发任务 threading.Thread(target=work, args=(i,)),再 t.start() new Worker(new URL(import.meta.url), { workerData: 30 }) await Task.Run(() => Fib(30)) go func() { ch <- "完成" }()
async/await async def hello(),里面 await asyncio.sleep(0.1) async function hello(),里面 await sleep(100) async Task<string> HelloAsync(),里面 await Task.Delay(100) 没有(第 19 章),函数照常写,要并发就放进 goroutine
等待多个任务 await asyncio.gather(fetch(1), fetch(2), fetch(3)) await Promise.all([fetchN(1), fetchN(2), fetchN(3)]) await Task.WhenAll(FetchAsync(1), FetchAsync(2), FetchAsync(3)) wg.Go(func() { a = fetch(1) }),再 wg.Wait()
锁 with lock:(lock = threading.Lock()) 没有(第 17 章),共享内存时用 Atomics.add(shared, 0, 5) lock (gate) { count++; }(Lock gate = new();) c.mu.Lock(),紧跟 defer c.mu.Unlock()
概念 Python JS/TS C# Go
读文本文件 p.read_text(encoding="utf-8") await readFile("note.txt", "utf8") await File.ReadAllLinesAsync("note.txt") data, err := os.ReadFile("note.txt")
写 JSON json.dumps(data, ensure_ascii=False, indent=2) JSON.stringify(data, null, 2) JsonSerializer.Serialize(u, AppJson.Default.User) json.Marshal(User{Name: "小明", …})
解析 JSON json.loads('{"n": 1, …}') JSON.parse('{"n": 1, …}') JsonSerializer.Deserialize(json, AppJson.Default.User) json.Unmarshal(data, &back)
概念 Python JS/TS C# Go
运行测试 python -m unittest node --test dotnet test go test ./...
概念 Python JS/TS C# Go
格式化代码 uv run ruff format .(第三方) npx prettier --write .(第三方) dotnet format go fmt ./...