npx skills add https://github.com/cxuu/golang-skills --skill go-naming规范性:根据 Google 官方 Go 风格指南,核心命名规则(MixedCaps,无下划线)是必需的。建议性指南提供了提高清晰度和可维护性的最佳实践。
命名应:
命名更像是一门艺术而非科学——Go 的名称往往比其他语言中的更短。
规范性:所有 Go 标识符必须使用 MixedCaps。
Go 使用 MixedCaps 或 mixedCaps(驼峰式),从不使用下划线(蛇形命名法)。
// 良好示例
MaxLength // 导出常量
maxLength // 未导出常量
userID // 变量
URLParser // 包含首字母缩写的类型
// 不良示例
MAX_LENGTH // 不使用 snake_case
max_length // 不使用下划线
User_Name // 名称中不使用下划线
名称仅在以下情况下可以包含下划线:
TestFoo_InvalidInput、广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
BenchmarkSort_LargeSlice注意:文件名不是 Go 标识符,可以包含下划线。
规范性:包名必须为小写且无下划线。
包名必须:
简洁且仅使用小写字母
无下划线(例如,tabwriter 而非 tab_writer)
不太可能与常见变量名冲突
// 良好示例:user, oauth2, k8s, tabwriter // 不良示例:user_service(含下划线), UserService(大写), count(与变量名冲突)
建议性:不要使用通用的包名。
避免使用会诱使用户在导入时重命名的名称:util、common、helper、model、base。优先使用具体的名称:stringutil、httpauth、configloader。
重命名导入时,本地名称必须遵循包命名规则:import foopb "path/to/foo_go_proto"(而不是带下划线的 foo_pb)。
建议性:单方法接口使用 "-er" 后缀。
按照惯例,单方法接口的名称由方法名加上 -er 后缀构成,以形成一个施动者名词:
// 标准库示例
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。
规范性:接收器变量必须是简短的缩写,并且要一致地使用。
接收器变量名必须:
| 长名称(不良) | 更好的名称 |
|---|---|
func (tray Tray) | func (t Tray) |
func (info *ResearchInfo) | func (ri *ResearchInfo) |
func (this *ReportWriter) | func (w *ReportWriter) |
func (self *Scanner) | func (s *Scanner) |
// 良好示例 - 一致且简短的接收器
func (c *Client) Connect() error
func (c *Client) Send(msg []byte) error
func (c *Client) Close() error
// 不良示例 - 不一致或过长的接收器
func (client *Client) Connect() error
func (cl *Client) Send(msg []byte) error
func (this *Client) Close() error
规范性:常量使用 MixedCaps,绝不使用 ALL_CAPS 或 K 前缀。
// 良好示例
const MaxPacketSize = 512
const defaultTimeout = 30 * time.Second
// 不良示例
const MAX_PACKET_SIZE = 512 // 不使用 snake_case
const kMaxBufferSize = 1024 // 不使用 K 前缀
建议性:常量应解释该值表示什么。
// 良好示例 - 名称解释了角色
const MaxRetries = 3
const DefaultPort = 8080
// 不良示例 - 名称仅描述了值
const Three = 3
const Port8080 = 8080
规范性:首字母缩写词在整个名称中保持大小写一致。
首字母缩写词(URL、ID、HTTP、API)应全部大写或全部小写:
| 英文 | 导出 | 未导出 |
|---|---|---|
| URL | URL | url |
| ID | ID | id |
| HTTP/API | HTTP | http |
| gRPC/iOS | GRPC/IOS | gRPC/iOS |
// 良好示例:HTTPClient, userID, ParseURL()
// 不良示例:HttpClient, orderId, ParseUrl()
建议性:对于简单的访问器,不要使用
Get前缀。
如果你有一个名为 owner(未导出)的字段,其 getter 方法应为 Owner()(导出),而不是 GetOwner()。如果需要 setter 方法,则为 SetOwner():
// 良好示例
owner := obj.Owner()
if owner != user {
obj.SetOwner(user)
}
// 不良示例:c.GetName(), u.GetEmail(), p.GetID()
对于开销较大的操作,使用 Compute 或 Fetch:db.FetchUser(id)、stats.ComputeAverage()。
建议性:对于 getter 使用名词性名称,对于动作使用动词性名称。
// 返回值的名词性名称
func (c *Config) JobName(key string) string
func (u *User) Permissions() []Permission
// 动作的动词性名称
func (c *Config) WriteDetail(w io.Writer) error
当函数仅因类型不同而有所区别时,在末尾包含类型:ParseInt()、ParseInt64()、AppendInt()、AppendInt64()。
对于明确的“主要”版本,省略类型:Marshal()(主要)、MarshalText()(变体)。
变量命名要在简洁和清晰之间取得平衡。关键原则:
基于作用域的长度:小作用域使用短名称(i、v);大作用域使用更长、更具描述性的名称
单字母约定:使用熟悉的模式(i 表示索引,r/w 表示读取器/写入器)
避免在名称中包含类型:使用 users 而不是 userSlice,使用 name 而不是 nameString
为未导出的全局变量添加前缀:为包级别的未导出变量/常量使用 _ 前缀,以防止遮蔽
// 良好示例 - 适合作用域的命名 for i, v := range items { ... } // 小作用域 pendingOrders := filterPending(orders) // 大作用域
// 良好示例 - 带前缀的未导出全局变量 const _defaultPort = 8080
详细指南:请参阅 references/VARIABLES.md
Go 的名称在使用时不应感觉重复。考虑完整的上下文:
包 + 符号:widget.New() 而不是 widget.NewWidget()
接收器 + 方法:p.Name() 而不是 p.ProjectName()
上下文 + 类型:在 sqldb 包中,使用 Connection 而不是 DBConnection
// 不良示例 - 重复 func (c *Config) WriteConfigTo(w io.Writer) error package db func LoadFromDatabase() error // db.LoadFromDatabase()
// 良好示例 - 简洁 func (c *Config) WriteTo(w io.Writer) error package db func Load() error // db.Load()
详细指南:请参阅 references/REPETITION.md
| 元素 | 规则 | 示例 |
|---|---|---|
| 包 | 小写,无下划线 | package httputil |
| 导出 | MixedCaps,首字母大写 | func ParseURL() |
| 未导出 | mixedCaps,首字母小写 | func parseURL() |
| 接收器 | 1-2 个字母的缩写 | func (c *Client) |
| 常量 | MixedCaps,绝不使用 ALL_CAPS | const MaxSize = 100 |
| 首字母缩写词 | 大小写一致 | userID、XMLAPI |
| 变量 | 长度与作用域大小相关 | i(小)、userCount(大) |
go-interfacesgo-style-corego-error-handlinggo-testinggo-defensivego-performance每周安装次数
147
代码仓库
GitHub 星标数
34
首次出现
2026年1月27日
安全审计
安装于
github-copilot139
gemini-cli137
codex137
kimi-cli136
amp136
opencode136
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.
Names should:
Naming is more art than science—Go names tend to be shorter than in other languages.
Normative : All Go identifiers must use MixedCaps.
Go uses MixedCaps or mixedCaps (camel case), never underscores (snake case).
// 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
Names may contain underscores only in these cases:
TestFoo_InvalidInput, BenchmarkSort_LargeSliceNote : Filenames are not Go identifiers and may contain underscores.
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
// Good: user, oauth2, k8s, tabwriter // Bad: user_service (underscores), UserService (uppercase), count (shadows var)
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.
When renaming imports, the local name must follow package naming rules: import foopb "path/to/foo_go_proto" (not foo_pb with underscore).
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:
// 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.
Normative : Receivers must be short abbreviations, used consistently.
Receiver variable names must be:
| 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) |
// 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
Normative : Constants use MixedCaps, never ALL_CAPS or K prefix.
// Good
const MaxPacketSize = 512
const defaultTimeout = 30 * time.Second
// Bad
const MAX_PACKET_SIZE = 512 // no snake_case
const kMaxBufferSize = 1024 // no K prefix
Advisory : Constants should explain what the value denotes.
// Good - names explain the role
const MaxRetries = 3
const DefaultPort = 8080
// Bad - names just describe the value
const Three = 3
const Port8080 = 8080
Normative : Initialisms maintain consistent case throughout.
Initialisms (URL, ID, HTTP, API) should be all uppercase or all lowercase:
| English | Exported | Unexported |
|---|---|---|
| URL | URL | url |
| ID | ID | id |
| HTTP/API | HTTP | http |
| gRPC/iOS | GRPC/ |
// Good: HTTPClient, userID, ParseURL()
// Bad: HttpClient, orderId, ParseUrl()
Advisory : Don't use
Getprefix 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():
// 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().
Advisory : Use noun-like names for getters, verb-like names for actions.
// 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
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).
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
For detailed guidance : See references/VARIABLES.md
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
// 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
| Element | Rule | Example |
|---|---|---|
| Package | lowercase, no underscores | package httputil |
| Exported | MixedCaps, starts uppercase | func ParseURL() |
| Unexported | mixedCaps, starts lowercase | func parseURL() |
| Receiver | 1-2 letter abbreviation | func (c *Client) |
| Constant | MixedCaps, never ALL_CAPS | const MaxSize = 100 |
go-interfacesgo-style-corego-error-handlinggo-testinggo-defensivego-performanceWeekly Installs
147
Repository
GitHub Stars
34
First Seen
Jan 27, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
github-copilot139
gemini-cli137
codex137
kimi-cli136
amp136
opencode136
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
106,200 周安装
Docassemble 表单构建器技能 - 创建智能动态问卷与文档生成工具
257 周安装
Fastify TypeScript 生产级后端框架指南:高性能 Node.js Web 开发与 JSON 模式验证
257 周安装
AI 演示文稿生成器 | 一键创建专业幻灯片,支持 Marp 格式输出
257 周安装
Mapbox搜索模式指南:地理编码、POI搜索与位置发现最佳实践
257 周安装
Zustand适配器:为json-render提供状态管理后端,支持嵌套切片与Zustand v5+
257 周安装
Blender MCP 插件使用指南:3D 场景自动化与 Python 脚本控制教程
257 周安装
IOSgRPC/iOS |
_// Good - scope-appropriate naming for i, v := range items { ... } // small scope pendingOrders := filterPending(orders) // larger scope
// Good - unexported global with prefix const _defaultPort = 8080
| Initialism | consistent case | userID, XMLAPI |
| Variable | length ~ scope size | i (small), userCount (large) |