golang-structs-interfaces
Skill3.4k starsChanged 2 months agoMITView on GitHub
Golang struct and interface design patterns — composition, embedding, type assertions, type switches, interface segregation, dependency injection via interfaces, struct field tags, and pointer vs value receivers. Use this skill when designing Go types, defining or implementing interfaces, embedding structs or interfaces, writing type assertions or type switches, adding struct field tags for JSON/YAML/DB serialization, or choosing between pointer and value receivers. Also use when the user asks about "accept interfaces, return structs", compile-time interface checks, or composing small interfaces into larger ones.
- Installs packages
4 other projects use a version of this, 3 of them edited.
Trending
Quiet since October.about the whole repository
Most recently taken up by
- rzisso/golang-skillsword for word, first seen Sep 16, 2026
- gccli/skillsedited, first seen Jul 27, 2026
- alexastrum/skledited, first seen Jun 12, 2026
- guynhsichngeodiec/cc-skills-golangedited, first seen Apr 7, 2026
Who's talking about samber/cc-skills-golang
- @golangch.bsky.social“A collection of Golang agentic skills that works #golang github.com/samber/cc-s...”Bluesky · Jul 16, 2026 · 10 likes
- @samber.bsky.social“My Go skill set: github.com/samber/cc-skills-golang npx skills add samber/cc-skills-golang Open to …”Bluesky · Mar 23, 2026 · 6 likes
- LobsterTrap/lola“[FEATURE] - Cherry Pick Skills”GitHub · May 6, 2026 · 3 reactions
- @golangch.bsky.social“Claude Code Skills for production-ready Golang projects #golang github.com/samber/cc-s...”Bluesky · Mar 29, 2026 · 3 likes
- A Hacker News story“A collection of 35 Golang Agent Skills”Hacker News · Mar 23, 2026 · 3 points
The biggest 5 of 45 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 45
Talked about on GitHub, Bluesky and Hacker News (45 times).
On GitHub · 41
- May 6, 2026[FEATURE] - Cherry Pick Skills — LobsterTrap/lola3 reactions · 1 comment
- Jul 16, 2026Skills with nested metadata maps are silently dropped during discovery — charmbracelet/crush1 reaction
- Mar 30, 2026[SUBMISSION] cc-skills-golang — ProSkillsMD/proskills1 reaction · 1 comment
- Oct 4, 2026claude-code-plugins.github.samber.cc-skills-golang: init at 2.0.0 — sudosubin/agents.nix0 reactions
- Oct 1, 2026agent-skills.github.samber.cc-skills-golang: init at 2.0.0 — sudosubin/agents.nix0 reactions
36 more on GitHub
- Sep 23, 2026Update skill: /samber-golang-structs-interfaces (safe risk) — aiskillstore/marketplace0 reactions
- Sep 23, 2026Update skill: /samber-golang-spf13-viper (safe risk) — aiskillstore/marketplace0 reactions
- Sep 23, 2026Update skill: /samber-golang-benchmark (medium risk) — aiskillstore/marketplacesays it tested it0 reactions
- Sep 23, 2026Update skill: /samber-golang-pkg-go-dev (high risk) — aiskillstore/marketplace0 reactions
- Sep 23, 2026Update skill: /samber-golang-samber-ro (safe risk) — aiskillstore/marketplace0 reactions
- Sep 23, 2026Update skill: /samber-golang-uber-fx (safe risk) — aiskillstore/marketplace0 reactions
- Sep 23, 2026Update skill: /samber-golang-stretchr-testify (safe risk) — aiskillstore/marketplace0 reactions
- Sep 23, 2026Update skill: /samber-golang-swagger (safe risk) — aiskillstore/marketplace0 reactions
- Sep 23, 2026Update skill: /samber-golang-stay-updated (safe risk) — aiskillstore/marketplace0 reactions
- Sep 6, 2026Update skill: /samber-golang-spf13-cobra (safe risk) — aiskillstore/marketplace0 reactions
- Sep 6, 2026Update skill: /samber-golang-cli (safe risk) — aiskillstore/marketplace0 reactions
- Sep 6, 2026Update skill: /samber-golang-lint (medium risk) — aiskillstore/marketplace0 reactions
- Sep 6, 2026Update skill: /samber-golang-samber-slog (medium risk) — aiskillstore/marketplace0 reactions
- Sep 6, 2026Update skill: /samber-golang-modernize (safe risk) — aiskillstore/marketplace0 reactions
- Sep 6, 2026Update skill: /samber-golang-samber-lo (safe risk) — aiskillstore/marketplace0 reactions
- Sep 6, 2026Update skill: /samber-golang-documentation (safe risk) — aiskillstore/marketplace0 reactions
- Sep 5, 2026corpus tier3 cites an id with no path: the largest source's provenance handle cannot be followed — jonhill90/agent-estate0 reactions · 1 comment
- Sep 3, 2026chore: sync upstream skills (auto) — marcioaltoe/skills0 reactions
- Sep 2, 2026chore: sync upstream skills (auto) — marcioaltoe/skills0 reactions
- Aug 19, 2026add `samber` golang skills — greenbone/opensight-golang-libraries0 reactions · 4 comments
- Jul 17, 2026fix: import skills with nested metadata and surface parse errors — gridctl/gridctl0 reactions
- Jul 17, 2026fix: skill import fails on nested metadata frontmatter with misleading 'no SKILL.md files found' error — gridctl/gridctl0 reactions
- Jul 16, 2026chore: sync upstream skills — marcioaltoe/skills0 reactions
- Jul 3, 2026New skill: /samber-golang-performance (safe risk) — aiskillstore/marketplace0 reactions
- Jul 1, 2026New skill: /samber-golang-error-handling (low risk) — aiskillstore/marketplace0 reactions
- Jul 1, 2026New skill: /samber-golang-code-style (low risk) — aiskillstore/marketplace0 reactions
- Jun 26, 2026Integrate samber/cc-skills-golang: install full general-purpose set + full-list reminder at plan & each scenario — ArcadeAI/safeword0 reactions · 3 comments
- Jun 26, 2026[FEATURE] Add Golang skills selectively — inference-gateway/cli0 reactions
- Jun 24, 2026chore(skills): sync upstream skills — marcioaltoe/skills0 reactions
- Jun 7, 2026feature/naming-linting-testing-skills — joekhosbayar/go-mightysays it tested it0 reactions
- May 22, 2026🔐 ci: pin + sandbox the skills install in claude-review.yml — martinciu/ccpulse0 reactions
- May 21, 2026🔐 ci: pin or sandbox the unpinned npx skills install in claude-review.yml — martinciu/ccpulse0 reactions · 1 comment
- Apr 25, 2026Audit candidate: samber/cc-skills-golang — xiaolai/nlpm0 reactions · 3 comments
- Mar 30, 2026[Resource]: cc-skills-golang — hesreallyhim/awesome-claude-code0 reactions · 1 comment
- Mar 29, 2026golang skills — sushichan044/dotfiles0 reactions
- Mar 22, 2026Add a claude code skills for Golang — jqueryscript/awesome-claude-code0 reactions
On Bluesky · 3
- Jul 16, 2026A collection of Golang agentic skills that works #golang github.com/samber/cc-s... — @golangch.bsky.social10 likes and reposts
- Mar 23, 2026My Go skill set: github.com/samber/cc-skills-golang npx skills add samber/cc-skills-golang Open to contributions. If you're building skills… — @samber.bsky.social6 likes and reposts
- Mar 29, 2026Claude Code Skills for production-ready Golang projects #golang github.com/samber/cc-s... — @golangch.bsky.social3 likes and reposts · 1 reply
On Hacker News · 1
- Mar 23, 2026A collection of 35 Golang Agent Skills3 points · 2 comments
Other versions4 projects use a version of this.
Word for word · 1
- rzisso/golang-skills★ 0100% same
Edited · 3
- alexastrum/skl★ 1074% same
- gccli/skills★ 074% same
- guynhsichngeodiec/cc-skills-golang★ 074% same
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository46 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- golang-benchmarkSkill
- golang-cliSkill
- golang-code-styleSkill
- golang-concurrencySkill
- golang-contextSkill
- golang-continuous-integrationSkill
- golang-databaseSkill
- golang-data-structuresSkill
- golang-dependency-injectionSkill
- golang-dependency-managementSkill
- golang-design-patternsSkill
- golang-documentationSkill
- golang-error-handlingSkill
- golang-google-wireSkill
- golang-goplsSkill
- golang-graphqlSkill
- golang-grpcSkill
- golang-how-toSkill
- golang-lintSkill
- golang-modernizeSkill
- golang-namingSkill
- golang-observabilitySkill
- golang-performanceSkill
- golang-pkg-go-devSkill
- golang-popular-librariesSkill
- golang-project-layoutSkill
- golang-refactoringSkill
- golang-safetySkill
- golang-samber-doSkill
- golang-samber-hotSkill
- golang-samber-loSkill
- golang-samber-moSkill
- golang-samber-oopsSkill
- golang-samber-roSkill
- golang-samber-slogSkill
- golang-securitySkill
- golang-spf13-cobraSkill
- golang-spf13-viperSkill
- golang-stay-updatedSkill
- golang-stretchr-testifySkill
- golang-swaggerSkill
- golang-testingSkill
- golang-troubleshootingSkill
- golang-uber-digSkill
- golang-uber-fxSkill
The file
We split this skill into the rules it gives an agent
1 rule. 1 is common, 0 are distinctive, and 0 are very specific to this project.
1
Common
Most of the 3 edited versions we read keep these.
0
Distinctive
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Common: line 167
Verify a type implements an interface at compile time with a blank identifier assignment.
“Common” is measured: kept by at least 6 in 10 of the 3 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Persona: You are a Go type system designer. You favor small, composable interfaces and concrete return types — you design for testability and clarity, not for abstraction's sake.
Community default. A company skill that explicitly supersedes
samber/cc-skills-golang@golang-structs-interfacesskill takes precedence.
Go Structs & Interfaces
Interface Design Principles
Keep Interfaces Small
"The bigger the interface, the weaker the abstraction." — Go Proverbs
Interfaces SHOULD have 1-3 methods. Small interfaces are easier to implement, mock, and compose. If you need a larger contract, compose it from small interfaces:
→ See samber/cc-skills-golang@golang-naming skill for interface naming conventions (method + "-er" suffix, canonical names)
type Reader interface {
Read(p []byte) (n int, err error)
}
type Writer interface {
Write(p []byte) (n int, err error)
}
// Composed from small interfaces
type ReadWriter interface {
Reader
Writer
}Compose larger interfaces from smaller ones:
type ReadWriteCloser interface {
io.Reader
io.Writer
io.Closer
}Define Interfaces Where They're Consumed
Interfaces Belong to Consumers.
Interfaces MUST be defined where consumed, not where implemented. This keeps the consumer in control of the contract and avoids importing a package just for its interface.
// package notification — defines only what it needs
type Sender interface {
Send(to, body string) error
}
type Service struct {
sender Sender
}The email package exports a concrete Client struct — it doesn't need to know about Sender.
Accept Interfaces, Return Structs
Functions SHOULD accept interface parameters for flexibility and return concrete types for clarity. Callers get full access to the returned type's fields and methods; consumers upstream can still assign the result to an interface variable if needed.
// Good — accepts interface, returns concrete
func NewService(store UserStore) *Service { ... }
// Bad — an interface return hides every other method of the concrete type from callers
func NewService(store UserStore) ServiceInterface { ... }Don't Create Interfaces Prematurely
"Don't design with interfaces, discover them."
An interface written before a second implementation exists is a guess about which methods will vary — and the guess is usually wrong, so the abstraction has to be reshaped anyway. Meanwhile it costs a layer of indirection that hides the concrete type from readers and tooling. Start with concrete types; extract an interface once a second consumer, a second implementation, or a test mock demands it.
// Bad — premature interface with a single implementation
type UserRepository interface {
FindByID(ctx context.Context, id string) (*User, error)
}
type userRepository struct { db *sql.DB }
// Good — start concrete, extract an interface later when needed
type UserRepository struct { db *sql.DB }Make the Zero Value Useful
Design structs so they work without explicit initialization. A well-designed zero value reduces constructor boilerplate and prevents nil-related bugs:
// Good — zero value is ready to use
var buf bytes.Buffer
buf.WriteString("hello")
var mu sync.Mutex
mu.Lock()
// Bad — zero value is broken, requires constructor
type Registry struct {
items map[string]Item // nil map, panics on write
}
// Good — lazy initialization guards the zero value
func (r *Registry) Register(name string, item Item) {
if r.items == nil {
r.items = make(map[string]Item)
}
r.items[name] = item
}Avoid any / interface{} When a Specific Type Will Do
Since Go 1.18+, MUST prefer generics over any for type-safe operations. Use any only at true boundaries where the type is genuinely unknown (e.g., JSON decoding, reflection):
// Bad — loses type safety
func Contains(slice []any, target any) bool { ... }
// Good — generic, type-safe
func Contains[T comparable](slice []T, target T) bool { ... }Key Standard Library Interfaces
| Interface | Package | Method |
Reader | io | Read(p []byte) (n int, err error) |
Writer | io | Write(p []byte) (n int, err error) |
Closer | io | Close() error |
Stringer | fmt | String() string |
error | builtin | Error() string |
Handler | net/http | ServeHTTP(ResponseWriter, *Request) |
Marshaler | encoding/json | MarshalJSON() ([]byte, error) |
Unmarshaler | encoding/json | UnmarshalJSON([]byte) error |
Canonical method signatures MUST be honored — if your type has a String() method, it must match fmt.Stringer. Don't invent ToString() or ReadData().
Compile-Time Interface Check
Verify a type implements an interface at compile time with a blank identifier assignment. Place it near the type definition:
var _ io.ReadWriter = (*MyBuffer)(nil)This costs nothing at runtime. If MyBuffer ever stops satisfying io.ReadWriter, the build fails immediately.
Type Assertions & Type Switches
Type assertions MUST use the comma-ok form (s, ok := val.(string)) — the single-value form panics on a type mismatch instead of branching. Use a type switch to dispatch on the dynamic type, and an assertion to a small optional interface (if f, ok := w.(Flusher); ok) to exploit richer implementations without widening the declared parameter type.
→ See Type Assertions & Type Switches for type switch ordering, nil cases, and the optional-behavior pattern.
Struct & Interface Embedding
Struct Embedding
Embedding promotes the inner type's methods and fields to the outer type — composition, not inheritance:
type Logger struct {
*slog.Logger
}
type Server struct {
Logger
addr string
}
// s.Info(...) works — promoted from slog.Logger through Logger
s := Server{Logger: Logger{slog.Default()}, addr: ":8080"}
s.Info("starting", "addr", s.addr)The receiver of promoted methods is the inner type, not the outer. The outer type can override by defining its own method with the same name.
When to Embed vs Named Field
| Use | When |
| Embed | You want to promote the full API of the inner type — the outer type "is a" enhanced version |
| Named field | You only need the inner type internally — the outer type "has a" dependency |
// Embed — Server exposes all http.Handler methods
type Server struct {
http.Handler
}
// Named field — Server uses the store but doesn't expose its methods
type Server struct {
store *DataStore
}Dependency Injection via Interfaces
Accept dependencies as interfaces in constructors. This decouples components and makes testing straightforward:
type UserStore interface {
FindByID(ctx context.Context, id string) (*User, error)
}
type UserService struct {
store UserStore
}
func NewUserService(store UserStore) *UserService {
return &UserService{store: store}
}In tests, pass a mock or stub that satisfies UserStore — no real database needed.
Struct Field Tags
Exported fields in serialized structs MUST have field tags — without one, the encoder falls back to the Go field name, so renaming a field silently changes the wire format:
type Order struct {
ID string `json:"id" db:"id"`
Total float64 `json:"total" db:"total"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
Internal string `json:"-" db:"-"`
}→ See Struct Fields: Tags and Copy Safety for the full tag directive table, the omitempty vs omitzero trap, and go vet diagnostics.
Pointer vs Value Receivers
Use pointer (s *Server) | Use value (s Server) |
| Method modifies the receiver | Receiver is small and immutable |
Receiver contains sync.Mutex or similar | Receiver is a basic type (int, string) |
| Receiver is a large struct | Method is a read-only accessor |
| Consistency: if any method uses a pointer, all should | Map and function values (already reference types) |
Receiver type MUST be consistent across all methods of a type — if one method uses a pointer receiver, all methods should.
Preventing Struct Copies with noCopy
A struct holding a mutex, a channel, or internal pointers breaks when copied: the copy duplicates the lock state, so two goroutines guard two different mutexes and the invariant disappears silently. Embed a noCopy sentinel so go vet reports every value copy, and pass such structs by pointer.
Diagnose: 1- go vet ./... — copylocks reports value copies of lock-bearing structs
→ See Struct Fields: Tags and Copy Safety for the noCopy implementation and how vet detects it.
Cross-References
- → See
samber/cc-skills-golang@golang-namingskill for interface naming conventions (Reader, Closer, Stringer) - → See
samber/cc-skills-golang@golang-design-patternsskill for functional options, constructors, and builder patterns - → See
samber/cc-skills-golang@golang-dependency-injectionskill for DI patterns using interfaces - → See
samber/cc-skills-golang@golang-code-styleskill for value vs pointer function parameters (distinct from receivers) - → See
samber/cc-skills-golang@golang-goplsskill for safe rename and theimplementInterfacecode action — renaming a method or receiver that participates in interface satisfaction updates every call site and refuses a rename that would silently break the interface, which grep/sed cannot detect
Common Mistakes
| Mistake | Fix |
| Large interfaces (5+ methods) | Split into focused 1-3 method interfaces, compose if needed |
| Defining interfaces in the implementor package | Define where consumed |
| Returning interfaces from constructors | Return concrete types |
| Bare type assertions without comma-ok | Always use v, ok := x.(T) |
| Embedding when you only need a few methods | Use a named field and delegate explicitly |
| Missing field tags on serialized structs | Tag all exported fields in marshaled types |
| Mixing pointer and value receivers on a type | Pick one and be consistent |
| Forgetting compile-time interface check | Add var _ Interface = (*Type)(nil) |
Using ToString() instead of String() | Honor canonical method names |
| Premature interface with a single implementation | Start concrete, extract interface when needed |
| Nil map/slice in zero value struct | Use lazy initialization in methods |
Using any for type-safe operations | Use generics ([T comparable]) instead |
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

