samber/cc-skills-golang/golang-structs-interfaces
Claude Code and agent skill by samber/cc-skills-golang
- community
Checking that the SKILL.md file is still in the repository.
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.
Install
npx vskill@latest install samber/cc-skills-golang/golang-structs-interfacesSKILL.md
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 supersedessamber/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)
Compose larger interfaces from smaller ones:
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.
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.
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.
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:
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):
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:
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:
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 |
Dependency Injection via Interfaces
Accept dependencies as interfaces in constructors. This decouples components and makes testing straightforward:
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:
→ 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 |
Security
- Security scanPassed, 90 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/golang-structs-interfaces/SKILL.md
Popularity
- Repository stars
- 3,336
- Repository forks
- 219
- 7-day trend score
- 41
Stars and forks are for the whole GitHub repository, not this skill alone. Refreshed 25 Mar 2026, 7 months ago.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/samber/cc-skills-golang/golang-structs-interfaces)