go-naming
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGo 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 or (camel case), never underscores (snake case).
MixedCapsmixedCapsgo
// 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语言使用或(驼峰式命名),绝对不能使用下划线(蛇形命名)。
MixedCapsmixedCapsgo
// 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 namesExceptions for Underscores
下划线的例外情况
Names may contain underscores only in these cases:
- Test functions: ,
TestFoo_InvalidInputBenchmarkSort_LargeSlice - Generated code: Package names only imported by generated code
- OS/cgo interop: Low-level libraries matching OS identifiers (rare)
Note: Filenames are not Go identifiers and may contain underscores.
仅在以下场景中,名称可以包含下划线:
- 测试函数:,
TestFoo_InvalidInputBenchmarkSort_LargeSlice - 生成代码:仅被生成代码导入的包名
- 操作系统/cgo交互:与操作系统标识符匹配的底层库(罕见情况)
注意:文件名不属于Go语言标识符,可以包含下划线。
Package Names
包命名
Normative: Packages must be lowercase with no underscores.
Package names must be:
- Concise and lowercase only
- No underscores (e.g., not
tabwriter)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: , , ,
, . Prefer specific names: , , .
utilcommonhelpermodelbasestringutilhttpauthconfigloader建议性指南:不要使用通用的包名。
避免使用会让用户在导入时不得不重命名的名称:、、、、。优先使用具体名称:、、。
utilcommonhelpermodelbasestringutilhttpauthconfigloaderImport Renaming
导入重命名
When renaming imports, the local name must follow package naming rules:
(not with underscore).
import foopb "path/to/foo_go_proto"foo_pb当重命名导入的包时,本地名称必须遵循包命名规则:(不能是带下划线的)。
import foopb "path/to/foo_go_proto"foo_pbInterface Names
接口命名
Advisory: One-method interfaces use "-er" suffix.
By convention, one-method interfaces are named by the method name plus an
suffix to construct an agent noun:
-ergo
// 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 (, , , ) and their
signatures. If your type implements a method with the same meaning as a
well-known type, use the same name—call it not .
ReadWriteCloseStringStringToString建议性指南:单方法接口使用“-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 }遵循标准方法名(、、、)及其签名。如果你的类型实现了与知名类型含义相同的方法,请使用相同的名称——应该叫而非。
ReadWriteCloseStringStringToStringReceiver 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 |
|---|---|
| |
| |
| |
| |
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个字母)
- 是类型本身的缩写
- 在该类型的所有方法中保持一致
| 长名称(不推荐) | 更佳名称 |
|---|---|
| |
| |
| |
| |
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() errorConstant 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 prefixName 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 = 8080Initialisms and Acronyms
首字母缩写词与缩写
Normative: Initialisms maintain consistent case throughout.
Initialisms (URL, ID, HTTP, API) should be all uppercase or all lowercase:
| English | Exported | Unexported |
|---|---|---|
| URL | | |
| ID | | |
| HTTP/API | | |
| gRPC/iOS | | |
go
// Good: HTTPClient, userID, ParseURL()
// Bad: HttpClient, orderId, ParseUrl()规范性要求:首字母缩写词需保持大小写一致。
首字母缩写词(URL、ID、HTTP、API)应全部大写或全部小写:
| 英文 | 导出标识符 | 非导出标识符 |
|---|---|---|
| URL | | |
| ID | | |
| HTTP/API | | |
| gRPC/iOS | | |
go
// Good: HTTPClient, userID, ParseURL()
// Bad: HttpClient, orderId, ParseUrl()Function and Method Names
函数与方法命名
Getters and Setters
Getter与Setter
Advisory: Don't useprefix for simple accessors.Get
If you have a field called (unexported), the getter should be
(exported), not . The setter, if needed, is :
ownerOwner()GetOwner()SetOwner()go
// Good
owner := obj.Owner()
if owner != user {
obj.SetOwner(user)
}
// Bad: c.GetName(), u.GetEmail(), p.GetID()Use or for expensive operations:
, .
ComputeFetchdb.FetchUser(id)stats.ComputeAverage()建议性指南:简单访问器不要使用前缀。Get
如果你有一个名为的非导出字段,对应的获取方法应为(导出方法),而非。如果需要设置方法,则为:
ownerOwner()GetOwner()SetOwner()go
// Good
owner := obj.Owner()
if owner != user {
obj.SetOwner(user)
}
// Bad: c.GetName(), u.GetEmail(), p.GetID()对于开销较大的操作,使用或:、。
ComputeFetchdb.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) errorType Suffixes
类型后缀
When functions differ only by type, include type at the end:
, , , .
ParseInt()ParseInt64()AppendInt()AppendInt64()For a clear "primary" version, omit the type:
(primary), (variant).
Marshal()MarshalText()当函数仅因类型不同而区分时,在名称末尾添加类型:、、、。
ParseInt()ParseInt64()AppendInt()AppendInt64()对于明确的“主要”版本,可省略类型:(主要版本)、(变体版本)。
Marshal()MarshalText()Variable Names
变量命名
Variable naming balances brevity with clarity. Key principles:
- Scope-based length: Short names (,
i) for small scopes; longer, descriptive names for larger scopesv - Single-letter conventions: Use familiar patterns (for index,
i/rfor reader/writer)w - Avoid type in name: Use not
users,userSlicenotnamenameString - 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 = 8080For detailed guidance: See references/VARIABLES.md
变量命名需在简洁性与清晰度之间取得平衡。核心原则:
- 基于作用域长度命名:小作用域使用短名称(、
i);大作用域使用更长、更具描述性的名称v - 单字母惯例:使用通用模式(表示索引,
i/r表示读取器/写入器)w - 避免在名称中包含类型:使用而非
users,userSlice而非namenameString - 非导出全局变量加前缀:包级非导出变量/常量使用前缀,避免被遮蔽
_
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: not
widget.New()widget.NewWidget() - Receiver + method: not
p.Name()p.ProjectName() - Context + type: In package , use
sqldbnotConnectionDBConnection
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而非ConnectionDBConnection
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
快速参考
| Element | Rule | Example |
|---|---|---|
| Package | lowercase, no underscores | |
| Exported | MixedCaps, starts uppercase | |
| Unexported | mixedCaps, starts lowercase | |
| Receiver | 1-2 letter abbreviation | |
| Constant | MixedCaps, never ALL_CAPS | |
| Initialism | consistent case | |
| Variable | length ~ scope size | |
| 元素 | 规则 | 示例 |
|---|---|---|
| 包 | 小写,无下划线 | |
| 导出标识符 | MixedCaps,首字母大写 | |
| 非导出标识符 | mixedCaps,首字母小写 | |
| 接收者 | 1-2个字母的缩写 | |
| 常量 | MixedCaps,禁止全大写 | |
| 首字母缩写词 | 大小写一致 | |
| 变量 | 长度与作用域大小匹配 | |
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