golang-naming

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
Community default. A company skill that explicitly supersedes
samber/cc-skills-golang@golang-naming
skill takes precedence.
社区默认规则。若存在明确取代
samber/cc-skills-golang@golang-naming
技能的公司内部技能,以公司技能为准。

Go Naming Conventions

Go命名规范

Go favors short, readable names. Capitalization controls visibility — uppercase is exported, lowercase is unexported. All identifiers MUST use MixedCaps, NEVER underscores.
"Clear is better than clever." — Go Proverbs
"Design the architecture, name the components, document the details." — Go Proverbs
To ignore a rule, just add a comment to the code.
Go语言偏好简短、可读性强的命名。大小写控制可见性——大写表示导出(对外可见),小写表示非导出(仅包内可见)。所有标识符必须使用MixedCaps命名法,绝对不能使用下划线。
“清晰胜于机巧。”——Go语言箴言
“先设计架构,再为组件命名,最后记录细节。”——Go语言箴言
若要忽略某条规则,只需在代码中添加注释说明即可。

Quick Reference

快速参考

ElementConventionExample
Packagelowercase, single word
json
,
http
,
tabwriter
Filelowercase, underscores OK
user_handler.go
Exported nameUpperCamelCase
ReadAll
,
HTTPClient
UnexportedlowerCamelCase
parseToken
,
userCount
Interfacemethod name +
-er
Reader
,
Closer
,
Stringer
StructMixedCaps noun
Request
,
FileHeader
ConstantMixedCaps (not ALL_CAPS)
MaxRetries
,
defaultTimeout
Receiver1-2 letter abbreviation
func (s *Server)
,
func (b *Buffer)
Error variable
Err
prefix
ErrNotFound
,
ErrTimeout
Error type
Error
suffix
PathError
,
SyntaxError
Constructor
New
(single type) or
NewTypeName
(multi-type)
ring.New
,
http.NewRequest
Boolean field
is
,
has
,
can
prefix on fields and methods
isReady
,
IsConnected()
Test function
Test
+ function name
TestParseToken
Acronymall caps or all lower
URL
,
HTTPServer
,
xmlParser
Variant: context
WithContext
suffix
FetchWithContext
,
QueryContext
Variant: in-place
In
suffix
SortIn()
,
ReverseIn()
Variant: error
Must
prefix
MustParse()
,
MustLoadConfig()
Option func
With
+ field name
WithPort()
,
WithLogger()
Enum (iota)type name prefix, zero-value = unknown
StatusUnknown
at 0,
StatusReady
Named returndescriptive, for docs only
(n int, err error)
Error stringlowercase (incl. acronyms), no punctuation
"image: unknown format"
,
"invalid id"
Import aliasshort, only on collision
mrand "math/rand"
,
pb "app/proto"
Format func
f
suffix
Errorf
,
Wrapf
,
Logf
Test table fields
got
/
expected
prefixes
input string
,
expected int
元素规范示例
小写、单单词
json
,
http
,
tabwriter
文件小写,允许使用下划线
user_handler.go
导出名称UpperCamelCase(大驼峰)
ReadAll
,
HTTPClient
非导出名称lowerCamelCase(小驼峰)
parseToken
,
userCount
接口方法名 +
-er
后缀
Reader
,
Closer
,
Stringer
结构体MixedCaps(驼峰)名词
Request
,
FileHeader
常量MixedCaps(驼峰)(非全大写)
MaxRetries
,
defaultTimeout
接收器1-2个字母的缩写
func (s *Server)
,
func (b *Buffer)
错误变量
Err
前缀
ErrNotFound
,
ErrTimeout
错误类型
Error
后缀
PathError
,
SyntaxError
构造函数
New
(单一类型)或
NewTypeName
(多类型)
ring.New
,
http.NewRequest
布尔字段字段和方法使用
is
has
can
前缀
isReady
,
IsConnected()
测试函数
Test
+ 函数名
TestParseToken
首字母缩写词全大写或全小写
URL
,
HTTPServer
,
xmlParser
变体:上下文
WithContext
后缀
FetchWithContext
,
QueryContext
变体:原地操作
In
后缀
SortIn()
,
ReverseIn()
变体:错误强制处理
Must
前缀
MustParse()
,
MustLoadConfig()
选项函数
With
+ 字段名
WithPort()
,
WithLogger()
枚举(iota)类型名前缀,零值为未知状态
StatusUnknown
位于0位,
StatusReady
命名返回值具备描述性,仅用于文档
(n int, err error)
错误字符串全小写(含首字母缩写词),无标点符号
"image: unknown format"
,
"invalid id"
导入别名简短,仅在命名冲突时使用
mrand "math/rand"
,
pb "app/proto"
格式化函数
f
后缀
Errorf
,
Wrapf
,
Logf
测试表格字段
got
/
expected
前缀
input string
,
expected int

MixedCaps

MixedCaps命名法

All Go identifiers MUST use
MixedCaps
(or
mixedCaps
). NEVER use underscores in identifiers — the only exceptions are test function subcases (
TestFoo_InvalidInput
), generated code, and OS/cgo interop. This is load-bearing, not cosmetic — Go's export mechanism relies on capitalization, and tooling assumes MixedCaps throughout.
go
// ✓ Good
MaxPacketSize
userCount
parseHTTPResponse

// ✗ Bad — these conventions conflict with Go's export mechanism and tooling expectations
MAX_PACKET_SIZE   // C/Python style
max_packet_size   // snake_case
kMaxBufferSize    // Hungarian notation
所有Go标识符必须使用
MixedCaps
(或
mixedCaps
)。绝对不能在标识符中使用下划线——唯一例外是测试函数子用例(
TestFoo_InvalidInput
)、生成的代码以及与操作系统/cgo交互的代码。这是Go语言的核心规则,而非表面性规则——Go的导出机制依赖大小写,且所有工具都默认遵循MixedCaps规范。
go
// ✓ 正确写法
MaxPacketSize
userCount
parseHTTPResponse

// ✗ 错误写法——这些命名规范与Go的导出机制及工具预期冲突
MAX_PACKET_SIZE   // C/Python风格
max_packet_size   // snake_case风格
kMaxBufferSize    // 匈牙利命名法

Avoid Stuttering

避免重复命名

Go call sites always include the package name, so repeating it in the identifier wastes the reader's time —
http.HTTPClient
forces parsing "HTTP" twice. A name MUST NOT repeat information already present in the package name, type name, or surrounding context.
go
// Good — clean at the call site
http.Client       // not http.HTTPClient
json.Decoder      // not json.JSONDecoder
user.New()        // not user.NewUser()
config.Parse()    // not config.ParseConfig()

// In package sqldb:
type Connection struct{}  // not DBConnection — "db" is already in the package name

// Anti-stutter applies to ALL exported types, not just the primary struct:
// In package dbpool:
type Pool struct{}        // not DBPool
type Status struct{}      // not PoolStatus — callers write dbpool.Status
type Option func(*Pool)   // not PoolOption
Go代码调用时总会包含包名,因此在标识符中重复包名会浪费读者时间——
http.HTTPClient
需要读者两次解析“HTTP”。标识符绝对不能重复已存在于包名、类型名或上下文环境中的信息。
go
// 正确写法——调用时简洁清晰
http.Client       // 而非http.HTTPClient
json.Decoder      // 而非json.JSONDecoder
user.New()        // 而非user.NewUser()
config.Parse()    // 而非config.ParseConfig()

// 在sqldb包中:
type Connection struct{}  // 而非DBConnection——“db”已包含在包名中

// 避免重复命名适用于所有导出类型,而非仅主结构体:
// 在dbpool包中:
type Pool struct{}        // 而非DBPool
type Status struct{}      // 而非PoolStatus——调用者会写dbpool.Status
type Option func(*Pool)   // 而非PoolOption

Frequently Missed Conventions

容易忽略的规范

These conventions are correct but non-obvious — they are the most common source of naming mistakes:
Constructor naming: When a package exports a single primary type, the constructor is
New()
, not
NewTypeName()
. This avoids stuttering — callers write
apiclient.New()
not
apiclient.NewClient()
. Use
NewTypeName()
only when a package has multiple constructible types (like
http.NewRequest
,
http.NewServeMux
).
Boolean struct fields: Unexported boolean fields MUST use
is
/
has
/
can
prefix —
isConnected
,
hasPermission
, not bare
connected
or
permission
. The exported getter keeps the prefix:
IsConnected() bool
. This reads naturally as a question and distinguishes booleans from other types.
Error strings are fully lowercase — including acronyms. Write
"invalid message id"
not
"invalid message ID"
, because error strings are often concatenated with other context (
fmt.Errorf("parsing token: %w", err)
) and mixed case looks wrong mid-sentence. Sentinel errors should include the package name as prefix:
errors.New("apiclient: not found")
.
Enum zero values: Always place an explicit
Unknown
/
Invalid
sentinel at iota position 0. A
var s Status
silently becomes 0 — if that maps to a real state like
StatusReady
, code can behave as if a status was deliberately chosen when it wasn't.
Subtest names: Table-driven test case names in
t.Run()
should be fully lowercase descriptive phrases:
"valid id"
,
"empty input"
— not
"valid ID"
or
"Valid Input"
.
这些规范是正确的,但并不直观——它们是命名错误的最常见来源:
构造函数命名:当包仅导出一种主要类型时,构造函数使用
New()
,而非
NewTypeName()
。这避免了重复命名——调用者写
apiclient.New()
而非
apiclient.NewClient()
。仅当包包含多种可构造类型时(如
http.NewRequest
http.NewServeMux
),才使用
NewTypeName()
布尔结构体字段:非导出布尔字段必须使用
is
/
has
/
can
前缀——如
isConnected
hasPermission
,而非直接使用
connected
permission
。导出的getter方法保留前缀:
IsConnected() bool
。这样读起来像自然的疑问句,且能区分布尔类型与其他类型。
错误字符串全小写——包括首字母缩写词。应写
"invalid message id"
而非
"invalid message ID"
,因为错误字符串常与其他上下文拼接(如
fmt.Errorf("parsing token: %w", err)
),句子中间的混合大小写看起来不协调。哨兵错误应包含包名作为前缀:
errors.New("apiclient: not found")
枚举零值:始终在iota位置0处显式设置
Unknown
/
Invalid
哨兵值。
var s Status
会默认初始化为0——如果该值映射到真实状态如
StatusReady
,代码可能会表现为状态是被刻意选择的,但实际上并未设置。
子测试名称
t.Run()
中表格驱动测试用例的名称应为全小写的描述性短语:
"valid id"
"empty input"
——而非
"valid ID"
"Valid Input"

Detailed Categories

详细分类

For complete rules, examples, and rationale, see:
  • Packages, Files & Import Aliasing — Package naming (single word, lowercase, no plurals), file naming conventions, import alias patterns (only use on collision to avoid cognitive load), and directory structure.
  • Variables, Booleans, Receivers & Acronyms — Scope-based naming (length matches scope:
    i
    for 3-line loops, longer names for package-level), single-letter receiver conventions (
    s
    for Server), acronym casing (URL not Url, HTTPServer not HttpServer), and boolean naming patterns (isReady, hasPrefix).
  • Functions, Methods & Options — Getter/setter patterns (Go omits
    Get
    so
    user.Name()
    reads naturally), constructor conventions (
    New
    or
    NewTypeName
    ), named returns (for documentation only), format function suffixes (
    Errorf
    ,
    Wrapf
    ), and functional options (
    WithPort
    ,
    WithLogger
    ).
  • Types, Constants & Errors — Interface naming (
    Reader
    ,
    Closer
    suffix with
    -er
    ), struct naming (nouns, MixedCaps), constants (MixedCaps, not ALL_CAPS), enums (type name prefix like
    StatusReady
    ), sentinel errors (
    ErrNotFound
    variables), error types (
    PathError
    suffix), and error message conventions (lowercase, no punctuation).
  • Test Naming — Test function naming (
    TestFunctionName
    ), table-driven test field conventions (
    input
    ,
    expected
    ), test helper naming, and subcase naming patterns.
如需完整规则、示例及原理,请查看:
  • 包、文件与导入别名 — 包命名(单单词、小写、非复数)、文件命名规范、导入别名模式(仅在命名冲突时使用,以避免认知负担)以及目录结构。
  • 变量、布尔值、接收器与首字母缩写词 — 基于作用域的命名(名称长度与作用域匹配:3行循环使用
    i
    ,包级变量使用较长名称)、单字母接收器规范(
    s
    代表Server)、首字母缩写词大小写(URL而非Url,HTTPServer而非HttpServer)以及布尔值命名模式(isReady、hasPrefix)。
  • 函数、方法与选项 — Getter/Setter模式(Go省略
    Get
    ,因此
    user.Name()
    读起来更自然)、构造函数规范(
    New
    NewTypeName
    )、命名返回值(仅用于文档)、格式化函数后缀(
    Errorf
    Wrapf
    )以及函数选项(
    WithPort
    WithLogger
    )。
  • 类型、常量与错误 — 接口命名(
    Reader
    Closer
    使用
    -er
    后缀)、结构体命名(名词、MixedCaps)、常量(MixedCaps,非全大写)、枚举(类型名前缀如
    StatusReady
    )、哨兵错误(
    ErrNotFound
    变量)、错误类型(
    PathError
    后缀)以及错误消息规范(全小写、无标点)。
  • 测试命名 — 测试函数命名(
    TestFunctionName
    )、表格驱动测试字段规范(
    input
    expected
    )、测试辅助函数命名以及子用例命名模式。

Common Mistakes

常见错误

MistakeFix
ALL_CAPS
constants
Go reserves casing for visibility, not emphasis — use
MixedCaps
(
MaxRetries
)
GetName()
getter
Go omits
Get
because
user.Name()
reads naturally at call sites. But
Is
/
Has
/
Can
prefixes are kept for boolean predicates:
IsHealthy() bool
not
Healthy() bool
Url
,
Http
,
Json
acronyms
Mixed-case acronyms create ambiguity (
HttpsUrl
— is it
Https+Url
?). Use all caps or all lower
this
or
self
receiver
Go methods are called frequently — use 1-2 letter abbreviation (
s
for
Server
) to reduce visual noise
util
,
helper
packages
These names say nothing about content — use specific names that describe the abstraction
http.HTTPClient
stuttering
Package name is always present at call site —
http.Client
avoids reading "HTTP" twice
user.NewUser()
constructor
Single primary type uses
New()
user.New()
avoids repeating the type name
connected bool
field
Bare adjective is ambiguous — use
isConnected
so the field reads as a true/false question
"invalid message ID"
error
Error strings must be fully lowercase including acronyms —
"invalid message id"
StatusReady
at iota 0
Zero value should be a sentinel —
StatusUnknown
at 0 catches uninitialized values
"not found"
error string
Sentinel errors should include the package name —
"mypackage: not found"
identifies the origin
userSlice
type-in-name
Types encode implementation detail —
users
describes what it holds, not how
Inconsistent receiver namesSwitching names across methods of the same type confuses readers — use one name consistently
snake_case
identifiers
Underscores conflict with Go's MixedCaps convention and tooling expectations — use
mixedCaps
Long names for short scopesName length should match scope —
i
is fine for a 3-line loop,
userIndex
is noise
Naming constants by valueValues change, roles don't —
DefaultPort
survives a port change,
Port8080
doesn't
FetchCtx()
context variant
WithContext
is the standard Go suffix —
FetchWithContext()
is instantly recognizable
sort()
in-place but no
In
Readers assume functions return new values.
SortIn()
signals mutation
parse()
panicking on error
MustParse()
warns callers that failure panics — surprises belong in the name
Mixing
With*
,
Set*
,
Use*
Consistency across the codebase —
With*
is the Go convention for functional options
Plural package namesGo convention is singular (
net/url
not
net/urls
) — keeps import paths consistent
Wrapf
without
f
suffix
The
f
suffix signals format-string semantics —
Wrapf
,
Errorf
tell callers to pass format args
Unnecessary import aliasesAliases add cognitive load. Only alias on collision —
mrand "math/rand"
Inconsistent concept namesUsing
user
/
account
/
person
for the same concept forces readers to track synonyms — pick one name
错误写法修正方案
ALL_CAPS
常量
Go语言使用大小写控制可见性,而非强调——使用
MixedCaps
(如
MaxRetries
GetName()
getter方法
Go省略
Get
前缀,因为
user.Name()
在调用时读起来更自然。但布尔断言方法保留
Is
/
Has
/
Can
前缀:
IsHealthy() bool
而非
Healthy() bool
Url
Http
Json
首字母缩写词
混合大小写的首字母缩写词会造成歧义(如
HttpsUrl
——是
Https+Url
吗?)。使用全大写或全小写
this
self
接收器
Go方法调用频繁——使用1-2个字母的缩写(如
Server
s
)以减少视觉干扰
util
helper
这些名称无法体现包的内容——使用能描述抽象概念的具体名称
http.HTTPClient
重复命名
调用时始终包含包名——
http.Client
避免重复读取“HTTP”
user.NewUser()
构造函数
单一主要类型使用
New()
——
user.New()
避免重复类型名
connected bool
字段
直接使用形容词会产生歧义——使用
isConnected
,使字段读起来像一个是非问题
"invalid message ID"
错误字符串
错误字符串必须全小写(包括首字母缩写词)——
"invalid message id"
StatusReady
位于iota 0处
零值应为哨兵值——
StatusUnknown
位于0位可捕获未初始化的值
"not found"
错误字符串
哨兵错误应包含包名——
"mypackage: not found"
可标识错误来源
userSlice
包含类型的名称
类型不应暴露实现细节——
users
描述存储的内容,而非存储方式
接收器名称不一致同一类型的不同方法使用不同接收器名称会混淆读者——始终使用统一的名称
snake_case
标识符
下划线与Go的MixedCaps规范及工具预期冲突——使用
mixedCaps
短作用域使用长名称名称长度应与作用域匹配——3行循环使用
i
即可,
userIndex
会造成视觉干扰
按值命名常量值会变化,角色不会——
DefaultPort
在端口变更后仍适用,
Port8080
则不行
FetchCtx()
上下文变体
WithContext
是Go的标准后缀——
FetchWithContext()
具有即时辨识度
sort()
原地操作但无
In
后缀
读者默认函数会返回新值。
SortIn()
可明确表示是原地修改
parse()
出错时panic
MustParse()
可警告调用者失败会触发panic——意外行为应体现在名称中
混合使用
With*
Set*
Use*
代码库内保持一致——
With*
是Go函数选项的标准命名方式
复数包名Go规范使用单数(
net/url
而非
net/urls
)——保持导入路径一致
Wrapf
f
后缀
f
后缀表示支持格式化字符串——
Wrapf
Errorf
提示调用者传入格式化参数
不必要的导入别名别名会增加认知负担。仅在命名冲突时使用——
mrand "math/rand"
概念命名不一致同一概念使用
user
/
account
/
person
会迫使读者跟踪同义词——选择统一的名称

Enforce with Linters

使用Linter强制执行

Many naming convention issues are caught automatically by linters:
revive
,
predeclared
,
misspell
,
errname
. See
samber/cc-skills-golang@golang-linter
skill for configuration and usage.
许多命名规范问题可通过Linter自动检测:
revive
predeclared
misspell
errname
。如需配置及使用方法,请查看
samber/cc-skills-golang@golang-linter
技能。

Cross-References

交叉引用

  • → See
    samber/cc-skills-golang@golang-code-style
    skill for broader formatting and style decisions
  • → See
    samber/cc-skills-golang@golang-structs-interfaces
    skill for interface naming depth and receiver design
  • → See
    samber/cc-skills-golang@golang-linter
    skill for automated enforcement (revive, predeclared, misspell, errname)
  • → 如需更广泛的格式与风格决策,请查看
    samber/cc-skills-golang@golang-code-style
    技能
  • → 如需接口命名细节与接收器设计,请查看
    samber/cc-skills-golang@golang-structs-interfaces
    技能
  • → 如需自动化强制执行(revive、predeclared、misspell、errname),请查看
    samber/cc-skills-golang@golang-linter
    技能