附录C:Python-Go语法对照速查表
附录C是Python与Go语法的快速对照表:变量声明、数据类型、控制流、函数、struct、接口等。用途:快速查找Python和Go的语法对应关系。
使用方法:按需查阅,或与第3章配合使用
| 概念 | Python | Go |
|---|---|---|
| 注释 | # 单行 | // 单行 |
| 多行注释 | """多行""" | /* 多行 */ |
| 打印 | print(x) | fmt.Println(x) |
| 类型声明 | x: int = 10 | var x int = 10 或 x := 10 |
| 常量 | x = 10(无const) | const x = 10 |
| Python | Go | 说明 |
|---|---|---|
int | int, int32, int64 | 整数 |
float | float32, float64 | 浮点数 |
bool | bool | 布尔 |
str | string | 字符串 |
list | slice ([]T) | 动态数组 |
dict | map[K]V | 键值对 |
tuple | struct | 定长集合 |
bytes | []byte | 字节数组 |
# Pythonx = 10x = "hello"name: str = "Alice"// Govar x int = 10var x = 10 // 类型推断x := 10 // 短声明(函数内)
var s string = "hello"s := "hello" // 类型推断| Python | Go | 说明 |
|---|---|---|
s + t | s + t | 拼接 |
f"Hello {name}" | fmt.Sprintf("Hello %s", name) | 格式化 |
len(s) | len(s) | 长度(字节) |
s[1:3] | s[1:3] | 切片 |
s.upper() | strings.ToUpper(s) | 大写 |
s.lower() | strings.ToLower(s) | 小写 |
s.split(",") | strings.Split(s, ",") | 分割 |
",".join(lst) | strings.Join(lst, ",") | 拼接 |
s.strip() | strings.TrimSpace(s) | 去空白 |
| Python | Go | 说明 |
|---|---|---|
[1, 2, 3] | []int{1, 2, 3} | 字面量 |
lst.append(x) | lst = append(lst, x) | 添加 |
lst[0] | lst[0] | 访问 |
lst[1:3] | lst[1:3] | 切片 |
len(lst) | len(lst) | 长度 |
for x in lst: | for _, v := range lst { } | 遍历 |
字典/Map
Section titled “字典/Map”| Python | Go | 说明 |
|---|---|---|
d = {} | m := make(map[K]V) | 创建 |
d["key"] = value | m["key"] = value | 设置 |
d["key"] | m["key"] | 获取 |
d.get("key", default) | m["key"](需检查) | 安全获取 |
del d["key"] | delete(m, "key") | 删除 |
for k, v in d.items(): | for k, v := range m { } | 遍历 |
len(d) | len(m) | 长度 |
# Pythonif x > 0: print("正数")elif x < 0: print("负数")else: print("零")// Goif x > 0 { fmt.Println("正数")} else if x < 0 { fmt.Println("负数")} else { fmt.Println("零")}# Pythonfor i in range(5): print(i)
for item in items: print(item)
while condition: print("loop")// Gofor i := 0; i < 5; i++ { fmt.Println(i)}
for _, v := range items { fmt.Println(v)}
for { // 无限循环 if condition { break }}| Python | Go |
|---|---|
def f(a, b): return a + b | func f(a, b int) int { return a + b } |
def f(*args): return sum(args) | func f(nums ...int) int { ... } |
def f(a, b=10): | func f(a int, b ...int) { } |
lambda x: x * 2 | func(x int) int { return x * 2 } |
# Pythontry: result = divide(10, 0)except ZeroDivisionError as e: print(f"错误: {e}")finally: cleanup()// Goresult, err := divide(10, 0)if err != nil { fmt.Println("错误:", err) return err}// defer cleanup()# Pythonclass User: def __init__(self, name, age): self.name = name self.age = age
def greet(self): print(f"Hello, {self.name}")
user = User("Alice", 30)user.greet()// Gotype User struct { Name string Age int}
func (u *User) Greet() { fmt.Printf("Hello, %s\n", u.Name)}
user := &User{Name: "Alice", Age: 30}user.Greet()# Python(无显式接口)class Writer: def write(self, data): pass
# 使用duck typingdef save(writer, data): writer.write(data)// Gotype Writer interface { Write([]byte) (int, error)}
// 隐式实现type User struct {}func (u *User) Write(data []byte) (int, error) { ... }异常 vs Panic
Section titled “异常 vs Panic”# Pythonraise ValueError("invalid value")try: risky()except Exception as e: print(e)// Gopanic("something wrong")defer func() { if r := recover(); r != nil { fmt.Println("recovered") }}()| Python | Go |
|---|---|
threading.Thread(target=f) | go f() |
threading.Lock() | sync.Mutex |
threading.Event() | sync.Cond |
queue.Queue | chan |
asyncio.gather() | goroutine + sync.WaitGroup |
| Python | Go |
|---|---|
import os | import "os" |
from os import getenv | 无(直接用os.Getenv) |
import os as m | import m "os" |
from . import module | import "package" |
| Python | Go |
|---|---|
int(x) | int(x) |
float(x) | float64(x) |
str(x) | strconv.Itoa(x) / fmt.Sprintf("%v", x) |
bytes(s) | []byte(s) |
list(s) | 无直接对应,需手动转换 |