Golang Structs Interfaces
Samuel BertheCommunityCreated by samberDistributed by Samuel Berthe
- Skill
- Guidelines
- Software development
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a comprehensive guide to Go type system design, focusing on idiomatic patterns for structs and interfaces. It emphasizes creating small, composable interfaces, defining them where they are consumed, and favoring concrete return types. The guidance covers essential Go concepts including struct embedding, dependency injection, type assertions, field tags for serialization, and the proper use of pointer versus value receivers to ensure code clarity, testability, and performance.
What it does
- Provides patterns for designing small, composable interfaces.
- Explains how to use struct embedding for composition.
- Details the use of type assertions and type switches for dynamic type handling.
- Outlines best practices for struct field tags in JSON/YAML/DB serialization.
- Guides the choice between pointer and value receivers.
- Demonstrates how to implement compile-time interface checks.
When to use it
- When designing new Go types or refactoring existing ones.
- When defining or implementing interfaces for dependency injection.
- When adding serialization tags to struct fields.
- When deciding between pointer and value receivers for methods.
- When you need to safely handle dynamic types using assertions or switches.
Advantages
- Promotes cleaner, more testable, and loosely coupled code.
- Reduces boilerplate through effective zero-value design.
- Ensures type safety and prevents common runtime panics.
- Aligns code with Go community idioms and standard library patterns.
Usage examples
- “How should I design an interface for a service that needs to send notifications?”
- The agent will advise defining a small, specific interface (e.g., Sender) within the consumer package, rather than the package that implements the notification logic.
- “Should I use a pointer or value receiver for my struct method?”
- The agent will provide a decision matrix based on whether the method modifies the receiver, the size of the struct, and the need for consistency across all methods.
- “How do I ensure my struct is correctly serialized to JSON?”
- The agent will explain how to add struct field tags and warn about common pitfalls like missing tags or incorrect zero-value handling.
- “How can I check if a type implements an interface at compile time?”
- The agent will provide the syntax for a blank identifier assignment, such as 'var _ io.Reader = (*MyType)(nil)'.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/samber/golang-structs-interfaces/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip golang-structs-interfaces.zip -d .agents/skills
Documentation by samber
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 |
Files
- ATTRIBUTION.mdAdded by AutoGineer932 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md11.9 KiB
- evals/evals.json13.3 KiB
- references/struct-fields.md3.7 KiB
- references/type-assertions.md2.2 KiB
evals/evals.json
[
{
"id": 1,
"name": "interface-at-consumer-not-implementor",
"description": "Tests whether the model defines interfaces where they are consumed, not where they are implemented",
"prompt": "I'm writing a Go notification service that can send emails. I have an email package with a Client struct that has a Send method. I also have a notification package that needs to use this email client. Where should I define the interface?",
"trap": "Without the skill, the model often puts the interface in the email package (the implementor). The skill says interfaces MUST be defined where consumed, not where implemented.",
"assertions": [
{"id": "1.1", "text": "Interface is defined in the notification package (the consumer), NOT in the email package"},
{"id": "1.2", "text": "Interface has only the methods the notification package needs (not the full email.Client API)"},
{"id": "1.3", "text": "Email package exports a concrete Client struct, not an interface"},
{"id": "1.4", "text": "Explains WHY: keeps the consumer in control of the contract, avoids importing a package just for its interface"},
{"id": "1.5", "text": "Notification service depends on its own interface, not on email package types"}
]
},
{
"id": 2,
"name": "return-structs-not-interfaces",
"description": "Tests whether the model returns concrete types from constructors, not interfaces",
"prompt": "I'm designing a Go package with a UserService that depends on a UserStore interface. Should my NewUserService constructor return *UserService or UserServiceInterface? Show me the constructor signature.",
"trap": "Without the skill, the model may suggest returning an interface for 'flexibility' or 'abstraction'. The skill says functions SHOULD return concrete types -- NEVER return interfaces from constructors.",
"assertions": [
{"id": "2.1", "text": "Constructor returns *UserService (concrete type), NOT an interface"},
{"id": "2.2", "text": "Constructor accepts UserStore as an interface parameter (accept interfaces)"},
{"id": "2.3", "text": "Explains WHY: callers get full access to the concrete type's fields/methods; consumers can assign to interface if needed"},
{"id": "2.4", "text": "Explicitly states that returning interfaces from constructors is bad practice"},
{"id": "2.5", "text": "The accept-interfaces-return-structs principle is stated or demonstrated"}
]
},
{
"id": 3,
"name": "premature-interface-trap",
"description": "Tests whether the model avoids creating interfaces prematurely when there is only one implementation",
"prompt": "I'm writing a Go application with a UserRepository that talks to PostgreSQL. It's the only database we'll ever use. Should I create a UserRepository interface and a concrete postgresUserRepository struct, or just use a concrete struct directly?",
"trap": "Without the skill, the model almost always suggests creating an interface 'for testability' even with a single implementation. The skill says NEVER create interfaces prematurely -- wait for 2+ implementations or a testability requirement.",
"assertions": [
{"id": "3.1", "text": "Recommends starting with a concrete struct (not an interface) when there is only one implementation"},
{"id": "3.2", "text": "Mentions the principle: don't design with interfaces, discover them"},
{"id": "3.3", "text": "Suggests extracting an interface LATER when a second consumer or test mock demands it"},
{"id": "3.4", "text": "Acknowledges that testability IS a valid reason to add an interface, but it should be a deliberate choice"},
{"id": "3.5", "text": "Does NOT reflexively recommend creating an interface just because it is a repository"}
]
},
{
"id": 4,
"name": "zero-value-useful-design",
"description": "Tests whether the model designs structs with useful zero values using lazy initialization",
"prompt": "I have a Go Registry struct that stores items in a map. Users are getting panics when they call Register without calling NewRegistry first. How should I fix this?",
"trap": "Without the skill, the model may just say 'always call the constructor' or add nil checks at every call site. The skill says to make the zero value useful with lazy initialization.",
"assertions": [
{"id": "4.1", "text": "Recommends lazy initialization in the Register method (if r.items == nil { r.items = make(...) })"},
{"id": "4.2", "text": "Mentions the Go principle: make the zero value useful"},
{"id": "4.3", "text": "The fix allows using var r Registry without calling a constructor"},
{"id": "4.4", "text": "Does NOT just say 'always use the constructor' as the primary fix"},
{"id": "4.5", "text": "References bytes.Buffer or sync.Mutex as stdlib examples of useful zero values"}
]
},
{
"id": 5,
"name": "embedding-vs-named-field",
"description": "Tests whether the model correctly distinguishes when to embed vs use a named field",
"prompt": "I have a Go Server struct that uses a DataStore for persistence and an http.Handler for routing. Should I embed both, use named fields for both, or mix? The Server should expose the Handler's ServeHTTP method but should NOT expose DataStore's internal methods to callers.",
"trap": "Without the skill, the model may embed both or use named fields for both. The skill has a clear rule: embed when you want to promote the full API ('is a'), named field when you only need it internally ('has a').",
"assertions": [
{"id": "5.1", "text": "Embeds http.Handler (to promote ServeHTTP to the Server)"},
{"id": "5.2", "text": "Uses a named field for DataStore (not embedded, because its methods should not be exposed)"},
{"id": "5.3", "text": "Explains the embed vs named field rule: embed for 'is a' (promote full API), named field for 'has a' (internal use)"},
{"id": "5.4", "text": "Mentions that embedding promotes ALL methods of the inner type, which can be undesirable"},
{"id": "5.5", "text": "Notes that the receiver of promoted methods is the inner type, not the outer type"}
]
},
{
"id": 6,
"name": "compile-time-interface-check",
"description": "Tests whether the model uses compile-time interface verification",
"prompt": "I have a Go type MyBuffer that should implement io.ReadWriter. How can I make sure the compiler catches it if I accidentally break the interface contract later?",
"trap": "Without the skill, the model may suggest writing a test or just relying on usage sites to catch it. The skill recommends the var _ Interface = (*Type)(nil) pattern.",
"assertions": [
{"id": "6.1", "text": "Uses var _ io.ReadWriter = (*MyBuffer)(nil) pattern"},
{"id": "6.2", "text": "Places the check near the type definition"},
{"id": "6.3", "text": "Explains that this costs nothing at runtime"},
{"id": "6.4", "text": "Explains that the build fails immediately if MyBuffer stops satisfying the interface"}
]
},
{
"id": 7,
"name": "type-assertion-comma-ok",
"description": "Bare type assertions panic on wrong type; comma-ok is required even when the type 'should always' be correct",
"prompt": "Review this Go event dispatcher and fix any issues:\n\n```go\ntype Event struct {\n Type string\n Payload any\n}\n\nfunc Dispatch(e Event) error {\n switch e.Type {\n case \"user.created\":\n payload := e.Payload.(*UserCreated)\n return handleUserCreated(payload)\n case \"order.placed\":\n payload := e.Payload.(*OrderPlaced)\n return handleOrderPlaced(payload)\n case \"payment.failed\":\n payload := e.Payload.(*PaymentFailed)\n return handlePaymentFailed(payload)\n default:\n return fmt.Errorf(\"unknown event type: %s\", e.Type)\n }\n}\n```\n\nA teammate says: 'The bare type assertions are fine here — we always put the right payload type for each event type, and we control all the callers. The comma-ok form just adds noise and extra if-checks.' Is the teammate correct? Fix the code if needed.",
"trap": "The teammate's argument sounds reasonable — the caller controls event construction and should always set the correct payload type. But bare type assertions panic at runtime on any mismatch (future code, deserialized events, tests with wrong setup). The model should reject the teammate's argument and use comma-ok form.",
"assertions": [
{"id": "7.1", "text": "Rejects the teammate's argument — bare type assertions panic at runtime on any type mismatch, regardless of how controlled the callers seem"},
{"id": "7.2", "text": "Uses comma-ok form for all three type assertions: payload, ok := e.Payload.(*UserCreated)"},
{"id": "7.3", "text": "Handles the !ok case by returning an error (not panicking) — e.g., 'unexpected payload type for user.created'"},
{"id": "7.4", "text": "Explains the failure mode: future code, deserialized events from external sources, or tests with wrong fixture setup will cause unrecoverable panics with bare assertions"}
]
},
{
"id": 8,
"name": "optional-behavior-type-assertion",
"description": "Tests whether the model uses type assertions for optional interface capabilities",
"prompt": "I'm writing a Go function that writes data to an io.Writer. Some writers support flushing (like bufio.Writer) but not all. I want to flush after writing IF the writer supports it, but not require all writers to implement Flush. How should I design this?",
"trap": "Without the skill, the model may create a WriteAndFlusher interface and require all callers to implement it. The skill shows the optional behavior pattern with type assertion.",
"assertions": [
{"id": "8.1", "text": "Defines a separate Flusher interface with just the Flush method"},
{"id": "8.2", "text": "Function parameter is io.Writer (not a combined interface)"},
{"id": "8.3", "text": "Uses type assertion (f, ok := w.(Flusher)) to check for flush capability"},
{"id": "8.4", "text": "Only calls Flush if the type assertion succeeds"},
{"id": "8.5", "text": "Mentions this pattern is used in the standard library (e.g. http.Flusher, io.ReaderFrom)"}
]
},
{
"id": 9,
"name": "nocopy-sentinel-struct",
"description": "Tests whether the model uses the noCopy sentinel to prevent struct copying",
"prompt": "I have a Go struct ConnPool that contains a sync.Mutex and a slice of connections. A junior developer accidentally passed it by value to a function, which caused a data race. How can I prevent this struct from being copied?",
"trap": "Without the skill, the model may just say 'always use pointers' or rely on code review. The skill shows the noCopy sentinel pattern that makes go vet catch accidental copies.",
"assertions": [
{"id": "9.1", "text": "Recommends embedding a noCopy sentinel struct"},
{"id": "9.2", "text": "noCopy implements Lock() and Unlock() methods (empty bodies)"},
{"id": "9.3", "text": "Explains that go vet will flag copies of structs containing noCopy"},
{"id": "9.4", "text": "Mentions this is the same technique used by sync.WaitGroup, sync.Mutex, or strings.Builder in the stdlib"},
{"id": "9.5", "text": "Shows that the struct should be passed by pointer after adding noCopy"}
]
},
{
"id": 10,
"name": "generics-over-any-interface",
"description": "Tests whether the model prefers generics over any/interface{} for type-safe operations",
"prompt": "I need to write a Go function that checks if a slice contains a given element. The function should work with any comparable type (ints, strings, etc.). What's the best approach?",
"trap": "Without the skill, the model may use []any and any parameters for compatibility. The skill says MUST prefer generics over any for type-safe operations (Go 1.18+).",
"assertions": [
{"id": "10.1", "text": "Uses generics with a type parameter: func Contains[T comparable](slice []T, target T) bool"},
{"id": "10.2", "text": "Does NOT use []any or interface{} parameters"},
{"id": "10.3", "text": "Uses the comparable constraint for the type parameter"},
{"id": "10.4", "text": "Explains WHY: generics preserve type safety, while any loses it"},
{"id": "10.5", "text": "Mentions that any should only be used at true boundaries where type is genuinely unknown (JSON decoding, reflection)"}
]
},
{
"id": 11,
"name": "receiver-consistency-rule",
"description": "Tests whether the model enforces consistent receiver types across all methods of a type",
"prompt": "I have a Go struct with 5 methods. Four use value receivers and one uses a pointer receiver because it modifies the struct. Is this fine?",
"trap": "Without the skill, the model may accept the mixed receiver approach as valid for each method. The skill says receiver type MUST be consistent -- if one method uses pointer, all should.",
"assertions": [
{"id": "11.1", "text": "Says mixing pointer and value receivers on the same type is wrong or not recommended"},
{"id": "11.2", "text": "Recommends making ALL methods use pointer receivers since one needs to mutate"},
{"id": "11.3", "text": "Explains WHY: consistency rule -- if any method uses a pointer receiver, all should"},
{"id": "11.4", "text": "Mentions that method sets differ for T and *T which affects interface satisfaction"}
]
}
]
Requirements and compatibility
Written for: Claude Code, OpenAI Codex
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Declares allowed tools, Claude Code frontmatter
The author says: Designed for Claude Code, Codex or similar harness, and for projects using Golang.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- samber
- Publisher
- Samuel Berthe (Community)
- Distributed by
- Samuel Berthe
- Source
- samber/cc-skills-golang · skills/golang-structs-interfaces · commit bb1d43d
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by samber or Samuel Berthe.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download golang-structs-interfaces.zip