go-declarations
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGo Declarations and Initialization
Go 声明与初始化
Quick Reference: var vs :=
快速参考:var 与 := 的对比
| Context | Use | Example |
|---|---|---|
| Top-level | | |
| Local with value | | |
| Local zero-value (intentional) | | |
| Type differs from expression | | |
Read references/SCOPE.md when deciding between var and := in complex initialization patterns or multi-return assignments.
| 场景 | 使用方式 | 示例 |
|---|---|---|
| 顶层作用域 | | |
| 局部作用域且赋值初始值 | | |
| 局部作用域且需显式零值 | | |
| 类型与表达式返回值不同 | 指定类型的 | |
当遇到复杂初始化模式或多返回值赋值,需选择var或:=时,可阅读references/SCOPE.md。
Group Similar Declarations
分组相似声明
Group related , , in parenthesized blocks. Separate
unrelated declarations into distinct blocks.
varconsttypego
// Bad
const a = 1
const b = 2
// Good
const (
a = 1
b = 2
)Inside functions, group adjacent vars even if unrelated:
go
var (
caller = c.name
format = "json"
timeout = 5 * time.Second
)将相关的、、放在带括号的块中。将不相关的声明拆分为独立的块。
varconsttypego
// 不推荐
const a = 1
const b = 2
// 推荐
const (
a = 1
b = 2
)在函数内部,即使变量不相关,也可将相邻的var声明分组:
go
var (
caller = c.name
format = "json"
timeout = 5 * time.Second
)Constants and iota
常量与iota
Start enums at one so the zero value represents invalid/unset:
go
const (
Add Operation = iota + 1
Subtract
Multiply
)Use zero when the default behavior is desirable (e.g., ).
LogToStdoutRead references/IOTA.md when designing iota enums with bitmask patterns, byte-size constants, or String() methods.
枚举从1开始,使零值代表无效/未设置状态:
go
const (
Add Operation = iota + 1
Subtract
Multiply
)当默认行为符合需求时(如),可从0开始。
LogToStdout当设计带有位掩码模式、字节大小常量或String()方法的iota枚举时,可阅读references/IOTA.md。
Variable Scope
变量作用域
Use if-init to limit scope when the result is only needed for the error check:
go
if err := os.WriteFile(name, data, 0644); err != nil {
return err
}Don't reduce scope if it forces deeper nesting or you need the result outside
the . Move constants into functions when only used there.
ifRead references/SCOPE.md when working with top-level declarations or choosing between var and := for local variables.
当仅需在错误检查中使用结果时,使用if-init缩小作用域:
go
if err := os.WriteFile(name, data, 0644); err != nil {
return err
}如果缩小作用域会导致更深的嵌套,或者需要在外部使用结果,则不要缩小作用域。当常量仅在函数内部使用时,将其移至函数内。
if处理顶层声明或为局部变量选择var与:=时,可阅读references/SCOPE.md。
Initializing Structs
结构体初始化
- Always use field names (enforced by ). Exception: test tables with ≤3 fields.
go vet - Omit zero-value fields — let Go set defaults.
- Use for zero-value structs:
varnotvar user Useruser := User{} - Use over
&T{}:new(T)sptr := &T{Name: "bar"}
Read references/STRUCTS.md when initializing structs with many fields, building slices of struct pointers, or choosing single-line vs multi-line format.
- 始终使用字段名(会强制检查)。例外情况:字段数≤3的测试表。
go vet - 省略零值字段——让Go自动设置默认值。
- 使用声明零值结构体:
var而非var user Useruser := User{} - 优先使用而非
&T{}:new(T)sptr := &T{Name: "bar"}
当初始化包含多个字段的结构体、构建结构体指针切片,或选择单行与多行格式时,可阅读references/STRUCTS.md。
Composite Literal Formatting
复合字面量格式化
Use field names for external package types. Match closing brace indentation
with the opening line. Omit repeated type names in slice/map literals
().
gofmt -sRead references/INITIALIZATION.md when working with complex composite literals, cuddled braces, or zero-value field decisions.
Read references/LITERALS.md when formatting complex composite literals.
对于外部包类型,使用字段名。闭合大括号的缩进需与起始行对齐。在切片/映射字面量中省略重复的类型名(可自动处理)。
gofmt -s处理复杂复合字面量、紧凑大括号或零值字段决策时,可阅读references/INITIALIZATION.md。
格式化复杂复合字面量时,可阅读references/LITERALS.md。
Initializing Maps
映射初始化
| Scenario | Use | Example |
|---|---|---|
| Empty, populated later | | |
| Nil declaration | | |
| Fixed entries at init | Literal | |
make()| 场景 | 使用方式 | 示例 |
|---|---|---|
| 空映射,后续会填充数据 | | |
| 声明nil映射 | | |
| 初始化时指定固定条目 | 字面量 | |
make()Raw String Literals
原始字符串字面量
Use backtick strings to avoid hand-escaped characters:
go
// Bad
wantError := "unknown name:\"test\""
// Good
wantError := `unknown name:"test"`Ideal for regex, SQL, JSON, and multi-line text.
使用反引号字符串避免手动转义字符:
go
// 不推荐
wantError := "unknown name:\"test\""
// 推荐
wantError := `unknown name:"test"`非常适合正则表达式、SQL、JSON和多行文本。
Prefer any
Over interface{}
anyinterface{}优先使用any
而非interface{}
anyinterface{}Go 1.18+: use instead of in all new code.
anyinterface{}Go 1.18及以上版本:在所有新代码中使用替代。
anyinterface{}Avoid Shadowing Built-In Names
避免遮蔽内置名称
Never use predeclared identifiers (, , , , ,
, , , , , , , , ,
, , ) as names. Use to detect.
errorstringlencapappendcopynewmakeclosedeletepanicrecoveranytruefalseniliotago vetgo
// Bad — shadows the builtin
var error string
// Good
var errorMessage stringRead references/SHADOWING.md when debugging issues where := creates new variables that shadow outer scope.
切勿使用预声明标识符(、、、、、、、、、、、、、、、、)作为变量名。可使用检测此类问题。
errorstringlencapappendcopynewmakeclosedeletepanicrecoveranytruefalseniliotago vetgo
// 不推荐 —— 遮蔽了内置标识符
var error string
// 推荐
var errorMessage string当调试因:=创建的新变量遮蔽外部作用域变量的问题时,可阅读references/SHADOWING.md。
Related Skills
相关技能
- Naming conventions: See go-naming when choosing variable names, constant names, or deciding name length by scope
- Data structures: See go-data-structures when choosing between and
new, or initializing slices and mapsmake - Control flow scoping: See go-control-flow when using if-init, redeclaration, or avoiding variable shadowing
:= - Capacity hints: See go-performance when pre-allocating maps or slices with known sizes
- 命名规范:选择变量名、常量名或根据作用域决定名称长度时,详见go-naming
- 数据结构:选择与
new,或初始化切片和映射时,详见go-data-structuresmake - 控制流作用域:使用if-init、重声明或避免变量遮蔽时,详见go-control-flow
:= - 容量提示:预分配已知大小的映射或切片时,详见go-performance