附录 B · Go → Rust 概念翻译大全

200+ 条对应关系

核心问题:Go 中的每个概念在 Rust 中对应什么?

这附录给你一个"翻译字典":Go 概念左 → Rust 概念右。注意:很多翻译不是 1:1,Rust 常常没有完全等价物,但你能找到"做相似事情的工具"。


B.1 基础类型与字面量

GoRust备注
inti32 / i64 / isizeGo int 平台相关,Rust 倾向显式
int8 / int16 / int32 / int64i8 / i16 / i32 / i64一致
uint8 (byte)u8一致
float32 / float64f32 / f64一致
boolbool一致
string (UTF-8)String / &strRust 区分 owned / borrowed
[]byteVec<u8> / &[u8]同上
runechar (4 字节 Unicode scalar)一致
nilOption::NoneRust 没有 null
true / falsetrue / false一致
0x1f, 1_000_0000x1f, 1_000_000字面量分隔符一致
const Pi = 3.14const PI: f64 = 3.14;Rust 要求类型

B.2 控制流

GoRust
if x > 0 { ... } else { ... }if x > 0 { ... } else { ... }
for i := 0; i < n; i++ {}for i in 0..n {}
for _, v := range items {}for v in &items {}
for { ... } / break / continueloop { ... } / break / continue
switch x { case 1: ... }match x { 1 => ..., _ => ... }
switch { case x>0: ... }match x { _ if x > 0 => ..., _ => ... }
defer f()Drop trait / RAII / scopeguard crate
panic("msg")panic!("msg")
recover()std::panic::catch_unwind
goto没有

B.3 函数与方法

GoRust
func add(a, b int) int { return a+b }fn add(a: i32, b: i32) -> i32 { a + b }
func (s Type) M() {}(value receiver)impl Type { fn m(self) {} }
func (s *Type) M() {}(pointer receiver)impl Type { fn m(&mut self) {} }
多返回值 (a, b, err)(a, b, Result) 或 tuple
variadic args ...intargs: &[i32] 或 slice / Vec
closure func(x int) int { return x+1 }|x: i32| x + 1(或 move |...| ...)
函数作参数 f func(int) intf: impl Fn(i32) -> i32 或 Box<dyn Fn...>
命名返回值没有(用 tuple 解构)

B.4 struct 与 interface

GoRust
type Point struct { X, Y float64 }struct Point { x: f64, y: f64 }
Point{X:1, Y:2}Point { x: 1.0, y: 2.0 }
anonymous structtuple struct struct Wrap(i32) 或 struct A { x: i32 }
embedded struct(组合)显式字段 + 实现 Deref(谨慎)
interface { Read(p []byte) (int, error) }trait Read { fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error>; }
interface{} (empty)Box<dyn Any>
structural typing(隐式实现)nominal,显式 impl Trait for Type
type assertion v.(*T)(x as &dyn Any).downcast_ref::<T>()
标签 \json:"name"``#[serde(rename = "name")]

B.5 错误处理

GoRust
if err != nil { return err }? 运算符 / Result::map_err
error interfaceResult<T, E> + std::error::Error trait
errors.New("msg")anyhow!("msg") / 自定义 enum
fmt.Errorf("ctx: %w", err)err.context("ctx")(anyhow)
errors.Is(err, ErrFoo)matches!(err, AppError::Foo)
errors.As(err, &target)用 enum 匹配
panic / recoverpanic! / catch_unwind(不推荐做 error handling)

B.6 并发

GoRust
go f()std::thread::spawn(|| f()) 或 tokio::spawn(async { f().await })
chan Tstd::sync::mpsc::channel() / tokio::sync::mpsc / crossbeam::channel
select { case ... }tokio::select! / crossbeam::select!
sync.Mutexstd::sync::Mutex<T> / tokio::sync::Mutex<T> / parking_lot::Mutex
sync.RWMutexstd::sync::RwLock<T> / parking_lot::RwLock
sync.WaitGrouptokio::task::JoinSet / Arc<AtomicUsize> + Notify
sync.Oncestd::sync::OnceLock<T>
context.Contexttokio_util::sync::CancellationToken + propagate via async fn
context.WithTimeouttokio::time::timeout(dur, fut)
atomic.AddInt32AtomicI32::fetch_add(1, Ordering::SeqCst)
GCownership / Drop / Rc / Arc

B.7 包管理

GoRust
go.modCargo.toml
go.sumCargo.lock
module example.com/foo[package] name = "foo"
import "fmt"use std::fmt;
package foomod foo; / 一个 crate 一个名字
internal/ 包pub(crate) 可见性
GOPATH / GOPROXYcrates.io / [source.crates-io]
vendoringcargo vendor
go mod tidycargo update + cargo udeps
build tagsfeature flags

B.8 测试

GoRust
func TestX(t *testing.T)#[test] fn x() {}
t.Errorf / t.Fatalfassert! / assert_eq! / panic!
Benchmark func BenchmarkX(b *testing.B)criterion c.bench_function("x", ...)
Exampledoc-test ```rust
go test ./...cargo test
race detector -raceMiri / RUSTFLAGS="-Z sanitizer=thread"
coverage go test -covercargo llvm-cov / tarpaulin
testing/quickproptest / quickcheck

B.9 常用标准库

GoRust
fmt.Printlnprintln!
fmt.Sprintfformat!
strings.Splits.split(',').collect::<Vec<_>>()
strings.BuilderString::new() + push_str
bytes.BufferVec<u8> 或 bytes::BytesMut
encoding/jsonserde_json
net/http serveraxum / actix-web
net/http clientreqwest
database/sqlsqlx / diesel
os.Openstd::fs::File::open
time.Now()std::time::Instant::now() / chrono::Utc::now()
time.Sleepstd::thread::sleep / tokio::time::sleep
loglog + env_logger 或 tracing
flag packageclap crate
os.Getenvstd::env::var
regexpregex crate
crypto/...ring / rustls / RustCrypto 套件
io.Reader / io.Writerstd::io::Read / Write

B.10 生态对应

用途GoRust
Web 框架gin / chi / echoaxum / actix-web
RPCgrpc-gotonic
数据库 ORMgorm / sqlxsqlx / sea-orm / diesel
日志 / 观测zap / zerologtracing
配置viperconfig / figment
CLIcobra / urfaveclap
序列化encoding/json / protoserde + serde_json / prost
任务调度robfig/crontokio-cron-scheduler
缓存 / KVredigo / go-redisredis-rs / fred
队列NATS / Kafka clientnats / rdkafka
测试 mockgomockmockall
性能分析pprofpprof-rs / cargo flamegraph
文档站点hugo / docusaurusmdBook(本书在用)

几条战略级差异

  1. Go 没有 borrow checker;Rust 没有 GC —— 编码风格的根本差异
  2. Go 的 zero-value 设计 vs Rust 的"必须显式初始化" —— Rust 让你少踩"看似为空,其实未定义"的坑
  3. Go 拥抱"代码量换显式";Rust 拥抱"类型表达力" —— Go 经典 if err != nil;Rust ? 一个字符
  4. Go interface{} 万能;Rust 鄙视 dyn Any —— Rust 偏 generic / trait bound,运行时反射几乎不用
  5. Go 是 productivity-first;Rust 是 correctness-first —— 两个语言适合的项目类型不同

本附录用法:遇到不熟悉的 Rust 概念时,搜表里的 Go 对应物,先有大致印象,再读正文章节。


📝 学习记录

项内容
起始日期
完成日期
卡点
关键收获
配套代码仓库链接