go-naming

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Go Naming Conventions

Go命名规范

Normative: Core naming rules (MixedCaps, no underscores) are required per Google's canonical Go style guide. Advisory guidance provides best practices for clarity and maintainability.
规范性要求:根据Google官方Go语言风格指南,必须遵守核心命名规则(使用MixedCaps,禁止使用下划线)。建议性指南则提供了提升代码清晰度和可维护性的最佳实践。

Core Principle

核心原则

Names should:
  • Not feel repetitive when used
  • Take context into consideration
  • Not repeat concepts that are already clear
Naming is more art than science—Go names tend to be shorter than in other languages.

命名应:
  • 在使用时不会显得重复
  • 结合上下文考虑
  • 不重复已经明确的概念
命名更偏向艺术而非科学——Go语言的命名通常比其他语言更简短。

MixedCaps (Required)

MixedCaps(强制要求)

Normative: All Go identifiers must use MixedCaps.
Go uses
MixedCaps
or
mixedCaps
(camel case), never underscores (snake case).
go
// Good
MaxLength    // exported constant
maxLength    // unexported constant
userID       // variable
URLParser    // type with initialism

// Bad
MAX_LENGTH   // no snake_case
max_length   // no underscores
User_Name    // no underscores in names
规范性要求:所有Go语言标识符必须使用MixedCaps。
Go语言使用
MixedCaps
mixedCaps
(驼峰式命名),绝对不能使用下划线(蛇形命名)。
go
// Good
MaxLength    // exported constant
maxLength    // unexported constant
userID       // variable
URLParser    // type with initialism

// Bad
MAX_LENGTH   // no snake_case
max_length   // no underscores
User_Name    // no underscores in names

Exceptions for Underscores

下划线的例外情况

Names may contain underscores only in these cases:
  1. Test functions:
    TestFoo_InvalidInput
    ,
    BenchmarkSort_LargeSlice
  2. Generated code: Package names only imported by generated code
  3. OS/cgo interop: Low-level libraries matching OS identifiers (rare)
Note: Filenames are not Go identifiers and may contain underscores.

仅在以下场景中,名称可以包含下划线:
  1. 测试函数
    TestFoo_InvalidInput
    ,
    BenchmarkSort_LargeSlice
  2. 生成代码:仅被生成代码导入的包名
  3. 操作系统/cgo交互:与操作系统标识符匹配的底层库(罕见情况)
注意:文件名不属于Go语言标识符,可以包含下划线。

Package Names

包命名

Normative: Packages must be lowercase with no underscores.
Package names must be:
  • Concise and lowercase only
  • No underscores (e.g.,
    tabwriter
    not
    tab_writer
    )
  • Not likely to shadow common variables
go
// Good: user, oauth2, k8s, tabwriter
// Bad: user_service (underscores), UserService (uppercase), count (shadows var)
规范性要求:包名必须为小写,且不能包含下划线。
包名必须:
  • 简洁且仅使用小写
  • 不包含下划线(例如:
    tabwriter
    而非
    tab_writer
  • 不会遮蔽常见变量
go
// Good: user, oauth2, k8s, tabwriter
// Bad: user_service (underscores), UserService (uppercase), count (shadows var)

Avoid Uninformative Names

避免无意义的名称

Advisory: Don't use generic package names.
Avoid names that tempt users to rename on import:
util
,
common
,
helper
,
model
,
base
. Prefer specific names:
stringutil
,
httpauth
,
configloader
.
建议性指南:不要使用通用的包名。
避免使用会让用户在导入时不得不重命名的名称:
util
common
helper
model
base
。优先使用具体名称:
stringutil
httpauth
configloader

Import Renaming

导入重命名

When renaming imports, the local name must follow package naming rules:
import foopb "path/to/foo_go_proto"
(not
foo_pb
with underscore).

当重命名导入的包时,本地名称必须遵循包命名规则:
import foopb "path/to/foo_go_proto"
(不能是带下划线的
foo_pb
)。

Interface Names

接口命名

Advisory: One-method interfaces use "-er" suffix.
By convention, one-method interfaces are named by the method name plus an
-er
suffix to construct an agent noun:
go
// Standard library examples
type Reader interface { Read(p []byte) (n int, err error) }
type Writer interface { Write(p []byte) (n int, err error) }
type Formatter interface { Format(f State, verb rune) }
type CloseNotifier interface { CloseNotify() <-chan bool }
Honor canonical method names (
Read
,
Write
,
Close
,
String
) and their signatures. If your type implements a method with the same meaning as a well-known type, use the same name—call it
String
not
ToString
.

建议性指南:单方法接口使用“-er”后缀。
按照惯例,单方法接口的命名方式为方法名加上“-er”后缀,构成施动名词:
go
// Standard library examples
type Reader interface { Read(p []byte) (n int, err error) }
type Writer interface { Write(p []byte) (n int, err error) }
type Formatter interface { Format(f State, verb rune) }
type CloseNotifier interface { CloseNotify() <-chan bool }
遵循标准方法名(
Read
Write
Close
String
)及其签名。如果你的类型实现了与知名类型含义相同的方法,请使用相同的名称——应该叫
String
而非
ToString

Receiver Names

接收者命名

Normative: Receivers must be short abbreviations, used consistently.
Receiver variable names must be:
  • Short (one or two letters)
  • Abbreviations for the type itself
  • Consistent across all methods of that type
Long Name (Bad)Better Name
func (tray Tray)
func (t Tray)
func (info *ResearchInfo)
func (ri *ResearchInfo)
func (this *ReportWriter)
func (w *ReportWriter)
func (self *Scanner)
func (s *Scanner)
go
// Good - consistent short receiver
func (c *Client) Connect() error
func (c *Client) Send(msg []byte) error
func (c *Client) Close() error

// Bad - inconsistent or long receivers
func (client *Client) Connect() error
func (cl *Client) Send(msg []byte) error
func (this *Client) Close() error

规范性要求:接收者必须使用简短缩写,且保持一致。
接收者变量名必须:
  • 简短(1-2个字母)
  • 是类型本身的缩写
  • 在该类型的所有方法中保持一致
长名称(不推荐)更佳名称
func (tray Tray)
func (t Tray)
func (info *ResearchInfo)
func (ri *ResearchInfo)
func (this *ReportWriter)
func (w *ReportWriter)
func (self *Scanner)
func (s *Scanner)
go
// Good - consistent short receiver
func (c *Client) Connect() error
func (c *Client) Send(msg []byte) error
func (c *Client) Close() error

// Bad - inconsistent or long receivers
func (client *Client) Connect() error
func (cl *Client) Send(msg []byte) error
func (this *Client) Close() error

Constant Names

常量命名

Normative: Constants use MixedCaps, never ALL_CAPS or K prefix.
go
// Good
const MaxPacketSize = 512
const defaultTimeout = 30 * time.Second

// Bad
const MAX_PACKET_SIZE = 512    // no snake_case
const kMaxBufferSize = 1024    // no K prefix
规范性要求:常量使用MixedCaps,绝对不能使用全大写或K前缀。
go
// Good
const MaxPacketSize = 512
const defaultTimeout = 30 * time.Second

// Bad
const MAX_PACKET_SIZE = 512    // no snake_case
const kMaxBufferSize = 1024    // no K prefix

Name by Role, Not Value

按作用命名,而非按值命名

Advisory: Constants should explain what the value denotes.
go
// Good - names explain the role
const MaxRetries = 3
const DefaultPort = 8080

// Bad - names just describe the value
const Three = 3
const Port8080 = 8080

建议性指南:常量名称应说明该值的用途。
go
// Good - names explain the role
const MaxRetries = 3
const DefaultPort = 8080

// Bad - names just describe the value
const Three = 3
const Port8080 = 8080

Initialisms and Acronyms

首字母缩写词与缩写

Normative: Initialisms maintain consistent case throughout.
Initialisms (URL, ID, HTTP, API) should be all uppercase or all lowercase:
EnglishExportedUnexported
URL
URL
url
ID
ID
id
HTTP/API
HTTP
http
gRPC/iOS
GRPC
/
IOS
gRPC
/
iOS
go
// Good: HTTPClient, userID, ParseURL()
// Bad: HttpClient, orderId, ParseUrl()

规范性要求:首字母缩写词需保持大小写一致。
首字母缩写词(URL、ID、HTTP、API)应全部大写或全部小写:
英文导出标识符非导出标识符
URL
URL
url
ID
ID
id
HTTP/API
HTTP
http
gRPC/iOS
GRPC
/
IOS
gRPC
/
iOS
go
// Good: HTTPClient, userID, ParseURL()
// Bad: HttpClient, orderId, ParseUrl()

Function and Method Names

函数与方法命名

Getters and Setters

Getter与Setter

Advisory: Don't use
Get
prefix for simple accessors.
If you have a field called
owner
(unexported), the getter should be
Owner()
(exported), not
GetOwner()
. The setter, if needed, is
SetOwner()
:
go
// Good
owner := obj.Owner()
if owner != user {
    obj.SetOwner(user)
}

// Bad: c.GetName(), u.GetEmail(), p.GetID()
Use
Compute
or
Fetch
for expensive operations:
db.FetchUser(id)
,
stats.ComputeAverage()
.
建议性指南:简单访问器不要使用
Get
前缀。
如果你有一个名为
owner
的非导出字段,对应的获取方法应为
Owner()
(导出方法),而非
GetOwner()
。如果需要设置方法,则为
SetOwner()
go
// Good
owner := obj.Owner()
if owner != user {
    obj.SetOwner(user)
}

// Bad: c.GetName(), u.GetEmail(), p.GetID()
对于开销较大的操作,使用
Compute
Fetch
db.FetchUser(id)
stats.ComputeAverage()

Naming Conventions

命名惯例

Advisory: Use noun-like names for getters, verb-like names for actions.
go
// Noun-like for returning values
func (c *Config) JobName(key string) string
func (u *User) Permissions() []Permission

// Verb-like for actions
func (c *Config) WriteDetail(w io.Writer) error
建议性指南:获取类方法使用类名词,动作类方法使用动词。
go
// Noun-like for returning values
func (c *Config) JobName(key string) string
func (u *User) Permissions() []Permission

// Verb-like for actions
func (c *Config) WriteDetail(w io.Writer) error

Type Suffixes

类型后缀

When functions differ only by type, include type at the end:
ParseInt()
,
ParseInt64()
,
AppendInt()
,
AppendInt64()
.
For a clear "primary" version, omit the type:
Marshal()
(primary),
MarshalText()
(variant).

当函数仅因类型不同而区分时,在名称末尾添加类型:
ParseInt()
ParseInt64()
AppendInt()
AppendInt64()
对于明确的“主要”版本,可省略类型:
Marshal()
(主要版本)、
MarshalText()
(变体版本)。

Variable Names

变量命名

Variable naming balances brevity with clarity. Key principles:
  • Scope-based length: Short names (
    i
    ,
    v
    ) for small scopes; longer, descriptive names for larger scopes
  • Single-letter conventions: Use familiar patterns (
    i
    for index,
    r
    /
    w
    for reader/writer)
  • Avoid type in name: Use
    users
    not
    userSlice
    ,
    name
    not
    nameString
  • Prefix unexported globals: Use
    _
    prefix for package-level unexported vars/consts to prevent shadowing
go
// Good - scope-appropriate naming
for i, v := range items { ... }           // small scope
pendingOrders := filterPending(orders)    // larger scope

// Good - unexported global with prefix
const _defaultPort = 8080
For detailed guidance: See references/VARIABLES.md

变量命名需在简洁性与清晰度之间取得平衡。核心原则:
  • 基于作用域长度命名:小作用域使用短名称(
    i
    v
    );大作用域使用更长、更具描述性的名称
  • 单字母惯例:使用通用模式(
    i
    表示索引,
    r
    /
    w
    表示读取器/写入器)
  • 避免在名称中包含类型:使用
    users
    而非
    userSlice
    name
    而非
    nameString
  • 非导出全局变量加前缀:包级非导出变量/常量使用
    _
    前缀,避免被遮蔽
go
// Good - scope-appropriate naming
for i, v := range items { ... }           // small scope
pendingOrders := filterPending(orders)    // larger scope

// Good - unexported global with prefix
const _defaultPort = 8080
详细指南:请参阅 references/VARIABLES.md

Avoiding Repetition

避免重复

Go names should not feel repetitive when used. Consider the full context:
  • Package + symbol:
    widget.New()
    not
    widget.NewWidget()
  • Receiver + method:
    p.Name()
    not
    p.ProjectName()
  • Context + type: In package
    sqldb
    , use
    Connection
    not
    DBConnection
go
// Bad - repetitive
func (c *Config) WriteConfigTo(w io.Writer) error
package db
func LoadFromDatabase() error  // db.LoadFromDatabase()

// Good - concise
func (c *Config) WriteTo(w io.Writer) error
package db
func Load() error              // db.Load()
For detailed guidance: See references/REPETITION.md

Go语言的命名在使用时不应显得重复。请考虑完整上下文:
  • 包 + 符号
    widget.New()
    而非
    widget.NewWidget()
  • 接收者 + 方法
    p.Name()
    而非
    p.ProjectName()
  • 上下文 + 类型:在
    sqldb
    包中,使用
    Connection
    而非
    DBConnection
go
// Bad - repetitive
func (c *Config) WriteConfigTo(w io.Writer) error
package db
func LoadFromDatabase() error  // db.LoadFromDatabase()

// Good - concise
func (c *Config) WriteTo(w io.Writer) error
package db
func Load() error              // db.Load()
详细指南:请参阅 references/REPETITION.md

Quick Reference

快速参考

ElementRuleExample
Packagelowercase, no underscores
package httputil
ExportedMixedCaps, starts uppercase
func ParseURL()
UnexportedmixedCaps, starts lowercase
func parseURL()
Receiver1-2 letter abbreviation
func (c *Client)
ConstantMixedCaps, never ALL_CAPS
const MaxSize = 100
Initialismconsistent case
userID
,
XMLAPI
Variablelength ~ scope size
i
(small),
userCount
(large)
元素规则示例
小写,无下划线
package httputil
导出标识符MixedCaps,首字母大写
func ParseURL()
非导出标识符mixedCaps,首字母小写
func parseURL()
接收者1-2个字母的缩写
func (c *Client)
常量MixedCaps,禁止全大写
const MaxSize = 100
首字母缩写词大小写一致
userID
,
XMLAPI
变量长度与作用域大小匹配
i
(小作用域),
userCount
(大作用域)

See Also

另请参阅

  • For interface design patterns:
    go-interfaces
  • For core style principles:
    go-style-core
  • For error handling patterns:
    go-error-handling
  • For testing best practices:
    go-testing
  • For defensive programming:
    go-defensive
  • For performance optimization:
    go-performance
  • 接口设计模式:
    go-interfaces
  • 核心风格原则:
    go-style-core
  • 错误处理模式:
    go-error-handling
  • 测试最佳实践:
    go-testing
  • 防御式编程:
    go-defensive
  • 性能优化:
    go-performance