golang-naming
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCommunity default. A company skill that explicitly supersedesskill takes precedence.samber/cc-skills-golang@golang-naming
社区默认规则。若存在明确取代技能的公司内部技能,以公司技能为准。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
快速参考
| Element | Convention | Example |
|---|---|---|
| Package | lowercase, single word | |
| File | lowercase, underscores OK | |
| Exported name | UpperCamelCase | |
| Unexported | lowerCamelCase | |
| Interface | method name + | |
| Struct | MixedCaps noun | |
| Constant | MixedCaps (not ALL_CAPS) | |
| Receiver | 1-2 letter abbreviation | |
| Error variable | | |
| Error type | | |
| Constructor | | |
| Boolean field | | |
| Test function | | |
| Acronym | all caps or all lower | |
| Variant: context | | |
| Variant: in-place | | |
| Variant: error | | |
| Option func | | |
| Enum (iota) | type name prefix, zero-value = unknown | |
| Named return | descriptive, for docs only | |
| Error string | lowercase (incl. acronyms), no punctuation | |
| Import alias | short, only on collision | |
| Format func | | |
| Test table fields | | |
| 元素 | 规范 | 示例 |
|---|---|---|
| 包 | 小写、单单词 | |
| 文件 | 小写,允许使用下划线 | |
| 导出名称 | UpperCamelCase(大驼峰) | |
| 非导出名称 | lowerCamelCase(小驼峰) | |
| 接口 | 方法名 + | |
| 结构体 | MixedCaps(驼峰)名词 | |
| 常量 | MixedCaps(驼峰)(非全大写) | |
| 接收器 | 1-2个字母的缩写 | |
| 错误变量 | | |
| 错误类型 | | |
| 构造函数 | | |
| 布尔字段 | 字段和方法使用 | |
| 测试函数 | | |
| 首字母缩写词 | 全大写或全小写 | |
| 变体:上下文 | | |
| 变体:原地操作 | | |
| 变体:错误强制处理 | | |
| 选项函数 | | |
| 枚举(iota) | 类型名前缀,零值为未知状态 | |
| 命名返回值 | 具备描述性,仅用于文档 | |
| 错误字符串 | 全小写(含首字母缩写词),无标点符号 | |
| 导入别名 | 简短,仅在命名冲突时使用 | |
| 格式化函数 | | |
| 测试表格字段 | | |
MixedCaps
MixedCaps命名法
All Go identifiers MUST use (or ). NEVER use underscores in identifiers — the only exceptions are test function subcases (), generated code, and OS/cgo interop. This is load-bearing, not cosmetic — Go's export mechanism relies on capitalization, and tooling assumes MixedCaps throughout.
MixedCapsmixedCapsTestFoo_InvalidInputgo
// ✓ 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标识符必须使用(或)。绝对不能在标识符中使用下划线——唯一例外是测试函数子用例()、生成的代码以及与操作系统/cgo交互的代码。这是Go语言的核心规则,而非表面性规则——Go的导出机制依赖大小写,且所有工具都默认遵循MixedCaps规范。
MixedCapsmixedCapsTestFoo_InvalidInputgo
// ✓ 正确写法
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 — forces parsing "HTTP" twice. A name MUST NOT repeat information already present in the package name, type name, or surrounding context.
http.HTTPClientgo
// 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 PoolOptionGo代码调用时总会包含包名,因此在标识符中重复包名会浪费读者时间——需要读者两次解析“HTTP”。标识符绝对不能重复已存在于包名、类型名或上下文环境中的信息。
http.HTTPClientgo
// 正确写法——调用时简洁清晰
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) // 而非PoolOptionFrequently 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 , not . This avoids stuttering — callers write not . Use only when a package has multiple constructible types (like , ).
New()NewTypeName()apiclient.New()apiclient.NewClient()NewTypeName()http.NewRequesthttp.NewServeMuxBoolean struct fields: Unexported boolean fields MUST use // prefix — , , not bare or . The exported getter keeps the prefix: . This reads naturally as a question and distinguishes booleans from other types.
ishascanisConnectedhasPermissionconnectedpermissionIsConnected() boolError strings are fully lowercase — including acronyms. Write not , because error strings are often concatenated with other context () and mixed case looks wrong mid-sentence. Sentinel errors should include the package name as prefix: .
"invalid message id""invalid message ID"fmt.Errorf("parsing token: %w", err)errors.New("apiclient: not found")Enum zero values: Always place an explicit / sentinel at iota position 0. A silently becomes 0 — if that maps to a real state like , code can behave as if a status was deliberately chosen when it wasn't.
UnknownInvalidvar s StatusStatusReadySubtest names: Table-driven test case names in should be fully lowercase descriptive phrases: , — not or .
t.Run()"valid id""empty input""valid ID""Valid Input"这些规范是正确的,但并不直观——它们是命名错误的最常见来源:
构造函数命名:当包仅导出一种主要类型时,构造函数使用,而非。这避免了重复命名——调用者写而非。仅当包包含多种可构造类型时(如、),才使用。
New()NewTypeName()apiclient.New()apiclient.NewClient()http.NewRequesthttp.NewServeMuxNewTypeName()布尔结构体字段:非导出布尔字段必须使用//前缀——如、,而非直接使用或。导出的getter方法保留前缀:。这样读起来像自然的疑问句,且能区分布尔类型与其他类型。
ishascanisConnectedhasPermissionconnectedpermissionIsConnected() bool错误字符串全小写——包括首字母缩写词。应写而非,因为错误字符串常与其他上下文拼接(如),句子中间的混合大小写看起来不协调。哨兵错误应包含包名作为前缀:。
"invalid message id""invalid message ID"fmt.Errorf("parsing token: %w", err)errors.New("apiclient: not found")枚举零值:始终在iota位置0处显式设置/哨兵值。会默认初始化为0——如果该值映射到真实状态如,代码可能会表现为状态是被刻意选择的,但实际上并未设置。
UnknownInvalidvar s StatusStatusReady子测试名称:中表格驱动测试用例的名称应为全小写的描述性短语:、——而非或。
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:for 3-line loops, longer names for package-level), single-letter receiver conventions (
ifor Server), acronym casing (URL not Url, HTTPServer not HttpServer), and boolean naming patterns (isReady, hasPrefix).s -
Functions, Methods & Options — Getter/setter patterns (Go omitsso
Getreads naturally), constructor conventions (user.Name()orNew), named returns (for documentation only), format function suffixes (NewTypeName,Errorf), and functional options (Wrapf,WithPort).WithLogger -
Types, Constants & Errors — Interface naming (,
Readersuffix withCloser), struct naming (nouns, MixedCaps), constants (MixedCaps, not ALL_CAPS), enums (type name prefix like-er), sentinel errors (StatusReadyvariables), error types (ErrNotFoundsuffix), and error message conventions (lowercase, no punctuation).PathError -
Test Naming — Test function naming (), table-driven test field conventions (
TestFunctionName,input), test helper naming, and subcase naming patterns.expected
如需完整规则、示例及原理,请查看:
-
包、文件与导入别名 — 包命名(单单词、小写、非复数)、文件命名规范、导入别名模式(仅在命名冲突时使用,以避免认知负担)以及目录结构。
-
变量、布尔值、接收器与首字母缩写词 — 基于作用域的命名(名称长度与作用域匹配:3行循环使用,包级变量使用较长名称)、单字母接收器规范(
i代表Server)、首字母缩写词大小写(URL而非Url,HTTPServer而非HttpServer)以及布尔值命名模式(isReady、hasPrefix)。s -
函数、方法与选项 — Getter/Setter模式(Go省略,因此
Get读起来更自然)、构造函数规范(user.Name()或New)、命名返回值(仅用于文档)、格式化函数后缀(NewTypeName、Errorf)以及函数选项(Wrapf、WithPort)。WithLogger -
类型、常量与错误 — 接口命名(、
Reader使用Closer后缀)、结构体命名(名词、MixedCaps)、常量(MixedCaps,非全大写)、枚举(类型名前缀如-er)、哨兵错误(StatusReady变量)、错误类型(ErrNotFound后缀)以及错误消息规范(全小写、无标点)。PathError -
测试命名 — 测试函数命名()、表格驱动测试字段规范(
TestFunctionName、input)、测试辅助函数命名以及子用例命名模式。expected
Common Mistakes
常见错误
| Mistake | Fix |
|---|---|
| Go reserves casing for visibility, not emphasis — use |
| Go omits |
| Mixed-case acronyms create ambiguity ( |
| Go methods are called frequently — use 1-2 letter abbreviation ( |
| These names say nothing about content — use specific names that describe the abstraction |
| Package name is always present at call site — |
| Single primary type uses |
| Bare adjective is ambiguous — use |
| Error strings must be fully lowercase including acronyms — |
| Zero value should be a sentinel — |
| Sentinel errors should include the package name — |
| Types encode implementation detail — |
| Inconsistent receiver names | Switching names across methods of the same type confuses readers — use one name consistently |
| Underscores conflict with Go's MixedCaps convention and tooling expectations — use |
| Long names for short scopes | Name length should match scope — |
| Naming constants by value | Values change, roles don't — |
| |
| Readers assume functions return new values. |
| |
Mixing | Consistency across the codebase — |
| Plural package names | Go convention is singular ( |
| The |
| Unnecessary import aliases | Aliases add cognitive load. Only alias on collision — |
| Inconsistent concept names | Using |
| 错误写法 | 修正方案 |
|---|---|
| Go语言使用大小写控制可见性,而非强调——使用 |
| Go省略 |
| 混合大小写的首字母缩写词会造成歧义(如 |
| Go方法调用频繁——使用1-2个字母的缩写(如 |
| 这些名称无法体现包的内容——使用能描述抽象概念的具体名称 |
| 调用时始终包含包名—— |
| 单一主要类型使用 |
| 直接使用形容词会产生歧义——使用 |
| 错误字符串必须全小写(包括首字母缩写词)—— |
| 零值应为哨兵值—— |
| 哨兵错误应包含包名—— |
| 类型不应暴露实现细节—— |
| 接收器名称不一致 | 同一类型的不同方法使用不同接收器名称会混淆读者——始终使用统一的名称 |
| 下划线与Go的MixedCaps规范及工具预期冲突——使用 |
| 短作用域使用长名称 | 名称长度应与作用域匹配——3行循环使用 |
| 按值命名常量 | 值会变化,角色不会—— |
| |
| 读者默认函数会返回新值。 |
| |
混合使用 | 代码库内保持一致—— |
| 复数包名 | Go规范使用单数( |
| |
| 不必要的导入别名 | 别名会增加认知负担。仅在命名冲突时使用—— |
| 概念命名不一致 | 同一概念使用 |
Enforce with Linters
使用Linter强制执行
Many naming convention issues are caught automatically by linters: , , , . See skill for configuration and usage.
revivepredeclaredmisspellerrnamesamber/cc-skills-golang@golang-linter许多命名规范问题可通过Linter自动检测:、、、。如需配置及使用方法,请查看技能。
revivepredeclaredmisspellerrnamesamber/cc-skills-golang@golang-linterCross-References
交叉引用
- → See skill for broader formatting and style decisions
samber/cc-skills-golang@golang-code-style - → See skill for interface naming depth and receiver design
samber/cc-skills-golang@golang-structs-interfaces - → See skill for automated enforcement (revive, predeclared, misspell, errname)
samber/cc-skills-golang@golang-linter
- → 如需更广泛的格式与风格决策,请查看技能
samber/cc-skills-golang@golang-code-style - → 如需接口命名细节与接收器设计,请查看技能
samber/cc-skills-golang@golang-structs-interfaces - → 如需自动化强制执行(revive、predeclared、misspell、errname),请查看技能
samber/cc-skills-golang@golang-linter