go-declarations

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Go Declarations and Initialization

Go 声明与初始化



Quick Reference: var vs :=

快速参考:var 与 := 的对比

ContextUseExample
Top-level
var
(always)
var _s = F()
Local with value
:=
s := "foo"
Local zero-value (intentional)
var
var filtered []int
Type differs from expression
var
with type
var _e error = F()
Read references/SCOPE.md when deciding between var and := in complex initialization patterns or multi-return assignments.

场景使用方式示例
顶层作用域
var
(始终使用)
var _s = F()
局部作用域且赋值初始值
:=
s := "foo"
局部作用域且需显式零值
var
var filtered []int
类型与表达式返回值不同指定类型的
var
var _e error = F()
当遇到复杂初始化模式或多返回值赋值,需选择var或:=时,可阅读references/SCOPE.md

Group Similar Declarations

分组相似声明

Group related
var
,
const
,
type
in parenthesized blocks. Separate unrelated declarations into distinct blocks.
go
// 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
)

将相关的
var
const
type
放在带括号的块中。将不相关的声明拆分为独立的块。
go
// 不推荐
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.,
LogToStdout
).
Read 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
)
当默认行为符合需求时(如
LogToStdout
),可从0开始。
当设计带有位掩码模式、字节大小常量或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
if
. Move constants into functions when only used there.
Read 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
    go vet
    ). Exception: test tables with ≤3 fields.
  • Omit zero-value fields — let Go set defaults.
  • Use
    var
    for zero-value structs
    :
    var user User
    not
    user := User{}
  • Use
    &T{}
    over
    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.

  • 始终使用字段名
    go vet
    会强制检查)。例外情况:字段数≤3的测试表。
  • 省略零值字段——让Go自动设置默认值。
  • 使用
    var
    声明零值结构体
    var user User
    而非
    user := 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 -s
).
Read 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

映射初始化

ScenarioUseExample
Empty, populated later
make(map[K]V)
m := make(map[string]int)
Nil declaration
var
var m map[string]int
Fixed entries at initLiteral
m := map[string]int{"a": 1}
make()
visually distinguishes empty-but-initialized from nil. Use size hints when the count is known.

场景使用方式示例
空映射,后续会填充数据
make(map[K]V)
m := make(map[string]int)
声明nil映射
var
var m map[string]int
初始化时指定固定条目字面量
m := map[string]int{"a": 1}
make()
可直观区分已初始化的空映射与nil映射。当已知元素数量时,可使用大小提示。

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{}

优先使用
any
而非
interface{}

Go 1.18+: use
any
instead of
interface{}
in all new code.

Go 1.18及以上版本:在所有新代码中使用
any
替代
interface{}

Avoid Shadowing Built-In Names

避免遮蔽内置名称

Never use predeclared identifiers (
error
,
string
,
len
,
cap
,
append
,
copy
,
new
,
make
,
close
,
delete
,
panic
,
recover
,
any
,
true
,
false
,
nil
,
iota
) as names. Use
go vet
to detect.
go
// Bad — shadows the builtin
var error string

// Good
var errorMessage string
Read references/SHADOWING.md when debugging issues where := creates new variables that shadow outer scope.

切勿使用预声明标识符(
error
string
len
cap
append
copy
new
make
close
delete
panic
recover
any
true
false
nil
iota
)作为变量名。可使用
go vet
检测此类问题。
go
// 不推荐 —— 遮蔽了内置标识符
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
    new
    and
    make
    , or initializing slices and maps
  • 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
    make
    ,或初始化切片和映射时,详见go-data-structures
  • 控制流作用域:使用if-init、
    :=
    重声明或避免变量遮蔽时,详见go-control-flow
  • 容量提示:预分配已知大小的映射或切片时,详见go-performance