К основному содержанию
скилл CX Codex

go-naming · eduardo-sl — скилл для Claude Code: что делает и как установить

Задаёт правила именования в Go по Effective Go: пакеты, методы, акронимы и ошибки. Помогает избежать заикания имён вроде order.OrderService.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add eduardo-sl/go-agent-skills --skill go-naming -a claude-code
Открыть на GitHub

Что делает go-naming

Скилл внедряет в ассистента правила нейминга из Effective Go и рекомендаций Go Code Review Comments. Он проверяет имена пакетов, файлов, интерфейсов, ресиверов и констант. Пакеты приводятся к нижнему регистру в единственном числе без мусорных названий вроде util или common. Скилл убирает дублирование имени пакета на месте вызова: вместо http.HTTPClient остаётся http.Client.

Правила задают единый регистр для аббревиатур (userID, ServeHTTP), убирают префикс Get у геттеров и следят за ресиверами: одна-две буквы от типа вместо this или self. Ошибки-сигналы получают префикс Err, а типы ошибок — суффикс Error.

Для проверок скиллу нужен установленный Go toolchain и доступ к gofmt. Глобальный рефакторинг этот набор правил не выполняет. Форматирование и сортировка импортов вынесены в отдельные скиллы.

Какие задачи решает

  • исправить заикание имён пакетов и структур вроде user.NewUser
  • привести аббревиатуры к единому регистру в userID или ServeHTTP
  • очистить геттеры от префикса Get
  • выбрать имена для сигнальных ошибок и типов ошибок

Примеры запросов агенту

  • Проверь нейминг в пакете internal/orders по правилам Go
  • Как назвать структуру клиента в пакете httpsign без заикания имён?
  • Отревьюй имена ресиверов и констант в файле cache.go

Как установить go-naming

1Через Skills CLI (Vercel)

npx skills add eduardo-sl/go-agent-skills --skill go-naming -a claude-code

2Вручную: положить файлы

~/.claude/skills/go-naming/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/go-naming/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о go-naming

Как установить go-naming в Claude Code?

Выполните команду npx skills add eduardo-sl/go-agent-skills --skill go-naming -a claude-code. Конфигурация навыка запишется в ~/.claude/skills/go-naming/SKILL.md.

Что проверяет скилл go-naming?

Он проверяет соответствие имён пакетов, методов, переменных, интерфейсов и ошибок стандартам Effective Go. Ассистент перестаёт предлагать имена с префиксом Get, мусорные пакеты helpers и повторы имени пакета в типах.

Выполняет ли go-naming автоматическое форматирование кода?

Нет, скилл отвечает только за правила именования. Форматирование кода, сортировка импортов и массовое переименование символов вынесены в другие инструменты автора.

Исходный текст

SKILL.md · MIT
---
name: go-naming
description: >
  Go naming conventions for packages, files, types, functions, methods,
  receivers, variables, constants, errors, acronyms and tests, grounded in
  Effective Go and Go Code Review Comments. Use when: "what should I name
  this", "name this package", "naming review", "is this name idiomatic",
  "stuttering names", "Get prefix", "acronym casing", "error variable name",
  "receiver name".
  Not for: formatting, imports and declarations (go-coding-standards),
  carrying out a rename across the codebase (go-semantic-tools,
  go-refactoring).
user-invocable: true
license: MIT
compatibility: Designed for Claude Code or similar AI coding agents working on Go projects. Requires the Go toolchain.
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(gofmt:*)
metadata:
  author: eduardo-sl
  version: "1.0.0"
---

# Go Naming

In Go the package name is part of every call site, capitalization decides
visibility, and short names are the norm. A good name reads well *where it
is used*, not where it is declared.

> Community default. A project skill or agent-config rule that explicitly
> supersedes `go-naming` takes precedence over this one.

Detailed reference material, loaded on demand:

- `references/examples.md` — before/after renames for every rule below,
  including the initialism and stuttering edge cases.

Read a reference file only when the summary below is not enough.

## 1. Quick Reference

| Element | Convention | Example |
|---|---|---|
| Package | short, lowercase, one word, singular | `order`, `httpsign`, `postgres` |
| File | lowercase, `_` allowed, named after its main type or concern | `order_service.go`, `order_service_test.go` |
| Exported identifier | `MixedCaps` | `ParseToken`, `MaxRetries` |
| Unexported identifier | `mixedCaps` | `parseToken`, `maxRetries` |
| Initialism | all one case | `URL`, `userID`, `ServeHTTP`, `xmlParser` |
| Getter / setter | `Owner()` / `SetOwner()` | never `GetOwner()` |
| Constructor | `New` for the package's main type, `NewThing` otherwise | `ring.New`, `http.NewRequest` |
| Panicking variant | `Must` prefix | `template.Must`, `regexp.MustCompile` |
| Functional option | `With` + setting | `WithTimeout`, `WithLogger` |
| One-method interface | method + `-er` | `Reader`, `Notifier` |
| Receiver | 1-2 letters, same on every method | `func (s *Server)` |
| Sentinel error | `Err` prefix (`err` unexported) | `ErrNotFound`, `errClosed` |
| Error type | `Error` suffix | `ValidationError` |
| Enum constant | type name prefix, zero = unknown | `StatusUnknown`, `StatusActive` |
| Test | `Test` + function, `Test` + type `_` method | `TestParse`, `TestCache_Get` |

## 2. Packages

- Short, lowercase, single word: no underscores, no `mixedCaps`, no plural
  (`order`, not `orders`).
- Name it after what it *provides*: `retry`, `httpsign`, `postgres`. Never
  `util`, `common`, `helpers`, `misc`, `base`, `models`, `types` — they
  say nothing and collect everything.
- The directory name and the package name match.
- Avoid names callers want for their variables (`url`, `user`, `buf`) when
  the package is imported widely; a call site with `u := user.New()` reads
  better than shadowing the package.

## 3. Don't Stutter

The package name is always present at the call site, so don't repeat it:

```go
// ✅ Good — reads once
http.Client       order.Service     user.New()     config.Load()

// ❌ Bad — says it twice
http.HTTPClient   order.OrderService user.NewUser() config.LoadConfig()
```

The rule covers every exported name in the package, not just the main
type: in package `dbpool`, `Pool`, `Status` and `Option` — not `DBPool`,
`PoolStatus`, `PoolOption`.

## 4. MixedCaps, Initialisms and Constants

- Every identifier is `MixedCaps` or `mixedCaps`. Underscores appear only
  in test names (`TestCache_Get`), generated code, and cgo.
- An initialism keeps one case throughout: `URL`, `ID`, `HTTP`, `JSON`,
  `API` — `userID`, `parseURL`, `ServeHTTP`, `HTTPServer`, `xmlHTTPRequest`.
  Never `UserId`, `ParseUrl`, `HttpServer`.
- Constants are `MixedCaps` like everything else: `MaxRetries`, not
  `MAX_RETRIES` — case already means "exported" in Go.
- Name constants for their role, not their value: `DefaultPort`, not
  `Port8080`.
- Do not shadow predeclared identifiers: `len`, `cap`, `new`, `make`,
  `close`, `copy`, `error`, `string`, `min`, `max`.

## 5. Functions and Methods

- Getters drop `Get`: `u.Name()`, and the setter is `u.SetName()`.
  `Is`/`Has`/`Can` stay on boolean predicates: `IsActive()`.
- Constructors: `New` when the package has one main type, `NewThing`
  otherwise. A constructor that panics on bad input is `MustThing`.
- Canonical names carry a contract. Call a method `Read`, `Write`,
  `Close`, `Flush`, `String`, `Error` or `ServeHTTP` only if it has the
  standard signature and meaning — and if it does, use that name
  (`String()`, never `ToString()`).
- Name for what the caller gets, not how it is computed: `Users()`, not
  `QueryAndBuildUserList()`.
- Format-string variants end in `f`: `Errorf`, `Logf`.

## 6. Variables and Receivers

- Name length grows with scope: `i`, `n`, `err`, `ctx`, `buf` inside a few
  lines; `retryTimeout`, `pendingOrders` across a function; full words at
  package level.
- Don't put the type in the name (`userSlice` → `users`, `nameStr` →
  `name`), and don't repeat context the reader already has (`order.ID`
  inside `type Order`, not `order.OrderID`).
- Receivers are one or two letters from the type (`s *Server`,
  `rw *responseWriter`), the same on every method of the type — never
  `this` or `self`.
- Unexported package-level variables may take a `_` prefix
  (`_defaultTimeout`) to keep them distinct from locals — the Uber style
  convention. Follow whichever the codebase already uses.
- Boolean names read as a question: `isReady`, `hasChildren`, `canRetry`.

## 7. Types and Interfaces

- Types are nouns: `Request`, `FileHeader`, `RetryPolicy`.
- A one-method interface is the method plus `-er`: `Reader`, `Notifier`,
  `Validator`. Never an `I` prefix or `Interface` suffix.
- Name an interface after the behavior the consumer needs, in the
  consumer's package (`orderStore` in the service), not after the
  implementation it happens to have.

## 8. Errors

- Exported sentinels `ErrNotFound`, unexported `errClosed`.
- Error types end in `Error`: `NotFoundError`, `SyntaxError`.
- Error strings are lowercase with no trailing punctuation, prefixed with
  the package or operation: `"order: invalid quantity"`. They get wrapped
  into longer messages, so they must read mid-sentence.

## 9. Enums and Tests

- Enum constants are prefixed with their type and start with an explicit
  `Unknown` at zero: `StatusUnknown`, `StatusActive`, `StatusClosed`.
- Tests: `TestParse`, `TestCache_Get`, `BenchmarkParse`, `ExampleCache_Get`
  (the example name must match a real identifier, or `go vet` complains).
- Subtest names are short lowercase phrases — `"empty input"`,
  `"expired token"` — because `go test -run 'TestParse/empty_input'`
  selects them.

## Applying a Rename

Rename with gopls, not search-and-replace: it follows the type graph and
refuses renames that would break interface satisfaction (the
go-semantic-tools skill). Then grep struct tags, templates and SQL for the
old name — gopls does not see them. Exported names in a published library
need a deprecation cycle (the go-refactoring skill).

## Verification Checklist

1. No package named `util`, `common`, `helpers`, `models`, `types`, `misc` or `base`
2. No exported name repeats its package name
3. Initialisms keep one case (`ID`, `URL`, `HTTP`); no `ALL_CAPS` constants
4. No `Get` prefix on getters; `Must` only on panicking functions
5. Canonical method names (`String`, `Read`, `Close`, …) have canonical signatures
6. Receivers are short and identical across a type's methods; no `this`/`self`
7. Sentinels use `Err`, error types end in `Error`, error strings are lowercase
8. Enum constants carry the type prefix and an `Unknown` zero value
9. No predeclared identifier is shadowed
10. Renames done with gopls; tags and templates checked afterwards

© eduardo-sl · MIT · eduardo-sl/go-agent-skills

Похожие скиллы

Все скиллы по теме «Языки программирования» →

Сначала — go-naming от других авторов.

go-naming cxuu Скилл следит за именами в Go: пакеты, типы, функции, константы, получатели. Пригодится, когда агент создаёт новые типы или экспортируемое API. CX Codex +1 1 200установок migrate-to-shoehorn Matt Pocock Переводит type assertions с as в тестах на функции из @total-typescript/shoehorn. Нужен для частичных объектов и намеренно неверных данных в проверках. 475 388установок write-swift emilkowalski Скилл помогает писать, проверять и переносить код на Swift с учётом модели языка. Подойдёт, когда нужно разобраться с конкурентностью, ошибкой или циклом удержания объектов. CX Codex +1 119 300установок megacave JuliusBrussee Переводит ответы ассистента на классический китайский язык (вэньянь) для экономии места на экране. Активируется командами /megacave или /caveman wenyan. CX Codex +1 25 400установок find-docs upstash Тянет актуальную документацию, справочники API и примеры кода для любой библиотеки через Context7 CLI. Пригодится, когда агент отвечает по устаревшим данным обучения. CX Codex +1 9 400установок typescript-advanced-types Seth Hobson Помогает агенту писать сложную типизацию TypeScript: generics, conditional types и преобразования типов. Нужен для библиотек, API-клиентов и строгих конфигураций. CX Codex 92 169установок smart-explore thedotmack Структурно ищет функции и классы через tree-sitter. Пригодится, когда нужно разобраться в кодовой базе без чтения всех файлов. CX Codex +1 7 300установок

Из того же набора34

go-performance-review Скилл ищет узкие места в Go-коде и помогает проверять оптимизации бенчмарками и профилями. Пригодится для ревью горячих путей и снижения аллокаций. CX Codex +1 ★ 83звёзд репо go-observability Скилл для Go-сервисов: помогает настроить структурные логи на log/slog, трейсы и метрики через OpenTelemetry, а также алерты по SLO. Пригодится, когда сервис уже в проде и нужно видеть, что в нём происходит. CX Codex +1 ★ 83звёзд репо go-defensive-coding Защищает код на Go от паник и скрытых багов: типизированные nil в интерфейсах, алиасинг слайсов, переполнение чисел и утечки ресурсов. CX Codex +1 ★ 83звёзд репо go-concurrency-review Скилл проверяет конкурентный код на Go: жизненный цикл горутин, каналы, общие данные и передачу контекста. Пригодится для ревью, поиска гонок и проектирования конвейеров. CX Codex +1 ★ 83звёзд репо go-modernize Скилл помогает применять современные возможности Go и стандартной библиотеки. Пригодится для точечных правок или модернизации пакета и модуля. CX Codex +1 ★ 83звёзд репо go-error-handling Скилл задаёт агенту правила работы с ошибками в Go: обёртка через %w, sentinel-ошибки, свои типы и errors.Is/errors.As. CX Codex +1 ★ 83звёзд репо go-documentation Скилл настраивает оформление комментариев godoc, тестовых примеров и файлов документации для Go-проектов. Помогает агенту следовать соглашениям Go 1.19+ без лишнего шума в коде. CX Codex +1 ★ 83звёзд репо go-data-structures Скилл помогает выбирать и безопасно использовать слайсы, карты и массивы в Go. Пригодится, когда нужно разобраться с append, nil-слайсами или порядком обхода карты. CX Codex +1 ★ 83звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой