[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6CFN8N9EKR5WXE7WSXNJTY8":3,"skill-same:01M6CFN8N9EKR5WXE7WSXNJTY8":125},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":59,"commitSha":60,"skillDirectory":61,"forksCount":62,"repositoryHtmlUrl":63,"repositoryHomepageUrl":6,"ownerHtmlUrl":64,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":65,"install":66,"resources":78},"01M6CFN8N9EKR5WXE7WSXNJTY8","golang-structs-interfaces",null,"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\u002FYAML\u002FDB 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.","rockcookies\u002Fskills","rockcookies","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F3498265?v=4","01M6CF9C16X3SDSKZX6ANH7HQM","Jacob He","01M6CF9C53JP821FCW6R9B00AJ",1,"MIT","https:\u002F\u002Fgithub.com\u002Frockcookies\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fsamber-golang\u002Fgolang-structs-interfaces\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"golang structs interfaces","golang","Composition","design patterns","dependency","use","write","read","json","projects","Bash","design","https","compile","harness","code","lint","codex","github","writing","2026-11-10 10:12:30",false,"---\nname: golang-structs-interfaces\ndescription: >-\n  Golang struct and interface design patterns — composition, embedding, type\n  assertions, type switches, interface segregation, dependency injection via\n  interfaces, struct field tags, and pointer vs value receivers. Use this skill\n  when designing Go types, defining or implementing interfaces, embedding\n  structs or interfaces, writing type assertions or type switches, adding struct\n  field tags for JSON\u002FYAML\u002FDB serialization, or choosing between pointer and\n  value receivers. Also use when the user asks about \"accept interfaces, return\n  structs\", compile-time interface checks, or composing small interfaces into\n  larger ones.\nuser-invocable: true\nlicense: MIT\ncompatibility: >-\n  Designed for Claude Code, Codex or similar harness, and for projects using\n  Golang.\nmetadata:\n  author: samber\n  version: 1.2.0\n  openclaw:\n    emoji: ?\n    homepage: https:\u002F\u002Fgithub.com\u002Fsamber\u002Fcc-skills-golang\n    requires:\n      bins:\n        - go\n    install: []\nallowed-tools: >-\n  Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent\n  AskUserQuestion\npaths:\n  - '**\u002F*.go'\n---\n\n**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.\n\n> **Community default.** A company skill that explicitly supersedes `golang-structs-interfaces` skill takes precedence.\n\n# Go Structs & Interfaces\n\n## Interface Design Principles\n\n### Keep Interfaces Small\n\n> \"The bigger the interface, the weaker the abstraction.\" — Go Proverbs\n\nInterfaces 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:\n\n→ See `golang-naming` skill for interface naming conventions (method + \"-er\" suffix, canonical names)\n\n```go\ntype Reader interface {\n    Read(p []byte) (n int, err error)\n}\n\ntype Writer interface {\n    Write(p []byte) (n int, err error)\n}\n\n\u002F\u002F Composed from small interfaces\ntype ReadWriter interface {\n    Reader\n    Writer\n}\n```\n\nCompose larger interfaces from smaller ones:\n\n```go\ntype ReadWriteCloser interface {\n    io.Reader\n    io.Writer\n    io.Closer\n}\n```\n\n### Define Interfaces Where They're Consumed\n\nInterfaces Belong to Consumers.\n\nInterfaces 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.\n\n```go\n\u002F\u002F package notification — defines only what it needs\ntype Sender interface {\n    Send(to, body string) error\n}\n\ntype Service struct {\n    sender Sender\n}\n```\n\nThe `email` package exports a concrete `Client` struct — it doesn't need to know about `Sender`.\n\n### Accept Interfaces, Return Structs\n\nFunctions 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.\n\n```go\n\u002F\u002F Good — accepts interface, returns concrete\nfunc NewService(store UserStore) *Service { ... }\n\n\u002F\u002F BAD — NEVER return interfaces from constructors\nfunc NewService(store UserStore) ServiceInterface { ... }\n```\n\n### Don't Create Interfaces Prematurely\n\n> \"Don't design with interfaces, discover them.\"\n\nNEVER create interfaces prematurely — wait for 2+ implementations or a testability requirement. Premature interfaces add indirection without value. Start with concrete types; extract an interface when a second consumer or a test mock demands it.\n\n```go\n\u002F\u002F Bad — premature interface with a single implementation\ntype UserRepository interface {\n    FindByID(ctx context.Context, id string) (*User, error)\n}\ntype userRepository struct { db *sql.DB }\n\n\u002F\u002F Good — start concrete, extract an interface later when needed\ntype UserRepository struct { db *sql.DB }\n```\n\n## Make the Zero Value Useful\n\nDesign structs so they work without explicit initialization. A well-designed zero value reduces constructor boilerplate and prevents nil-related bugs:\n\n```go\n\u002F\u002F Good — zero value is ready to use\nvar buf bytes.Buffer\nbuf.WriteString(\"hello\")\n\nvar mu sync.Mutex\nmu.Lock()\n\n\u002F\u002F Bad — zero value is broken, requires constructor\ntype Registry struct {\n    items map[string]Item \u002F\u002F nil map, panics on write\n}\n\n\u002F\u002F Good — lazy initialization guards the zero value\nfunc (r *Registry) Register(name string, item Item) {\n    if r.items == nil {\n        r.items = make(map[string]Item)\n    }\n    r.items[name] = item\n}\n```\n\n## Avoid `any` \u002F `interface{}` When a Specific Type Will Do\n\nSince 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):\n\n```go\n\u002F\u002F Bad — loses type safety\nfunc Contains(slice []any, target any) bool { ... }\n\n\u002F\u002F Good — generic, type-safe\nfunc Contains[T comparable](slice []T, target T) bool { ... }\n```\n\n## Key Standard Library Interfaces\n\n| Interface     | Package         | Method                                |\n| ------------- | --------------- | ------------------------------------- |\n| `Reader`      | `io`            | `Read(p []byte) (n int, err error)`   |\n| `Writer`      | `io`            | `Write(p []byte) (n int, err error)`  |\n| `Closer`      | `io`            | `Close() error`                       |\n| `Stringer`    | `fmt`           | `String() string`                     |\n| `error`       | builtin         | `Error() string`                      |\n| `Handler`     | `net\u002Fhttp`      | `ServeHTTP(ResponseWriter, *Request)` |\n| `Marshaler`   | `encoding\u002Fjson` | `MarshalJSON() ([]byte, error)`       |\n| `Unmarshaler` | `encoding\u002Fjson` | `UnmarshalJSON([]byte) error`         |\n\nCanonical method signatures MUST be honored — if your type has a `String()` method, it must match `fmt.Stringer`. Don't invent `ToString()` or `ReadData()`.\n\n## Compile-Time Interface Check\n\nVerify a type implements an interface at compile time with a blank identifier assignment. Place it near the type definition:\n\n```go\nvar _ io.ReadWriter = (*MyBuffer)(nil)\n```\n\nThis costs nothing at runtime. If `MyBuffer` ever stops satisfying `io.ReadWriter`, the build fails immediately.\n\n## Type Assertions & Type Switches\n\n### Safe Type Assertion\n\nType assertions MUST use the comma-ok form to avoid panics:\n\n```go\n\u002F\u002F Good — safe\ns, ok := val.(string)\nif !ok {\n    \u002F\u002F handle\n}\n\n\u002F\u002F Bad — panics if val is not a string\ns := val.(string)\n```\n\n### Type Switch\n\nDiscover the dynamic type of an interface value:\n\n```go\nswitch v := val.(type) {\ncase string:\n    fmt.Println(v)\ncase int:\n    fmt.Println(v * 2)\ncase io.Reader:\n    io.Copy(os.Stdout, v)\ndefault:\n    fmt.Printf(\"unexpected type %T\\n\", v)\n}\n```\n\n### Optional Behavior with Type Assertions\n\nCheck if a value supports additional capabilities without requiring them upfront:\n\n```go\ntype Flusher interface {\n    Flush() error\n}\n\nfunc writeData(w io.Writer, data []byte) error {\n    if _, err := w.Write(data); err != nil {\n        return err\n    }\n    \u002F\u002F Flush only if the writer supports it\n    if f, ok := w.(Flusher); ok {\n        return f.Flush()\n    }\n    return nil\n}\n```\n\nThis pattern is used extensively in the standard library (e.g., `http.Flusher`, `io.ReaderFrom`).\n\n## Struct & Interface Embedding\n\n### Struct Embedding\n\nEmbedding promotes the inner type's methods and fields to the outer type — composition, not inheritance:\n\n```go\ntype Logger struct {\n    *slog.Logger\n}\n\ntype Server struct {\n    Logger\n    addr string\n}\n\n\u002F\u002F s.Info(...) works — promoted from slog.Logger through Logger\ns := Server{Logger: Logger{slog.Default()}, addr: \":8080\"}\ns.Info(\"starting\", \"addr\", s.addr)\n```\n\nThe 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.\n\n### When to Embed vs Named Field\n\n| Use | When |\n| --- | --- |\n| **Embed** | You want to promote the full API of the inner type — the outer type \"is a\" enhanced version |\n| **Named field** | You only need the inner type internally — the outer type \"has a\" dependency |\n\n```go\n\u002F\u002F Embed — Server exposes all http.Handler methods\ntype Server struct {\n    http.Handler\n}\n\n\u002F\u002F Named field — Server uses the store but doesn't expose its methods\ntype Server struct {\n    store *DataStore\n}\n```\n\n## Dependency Injection via Interfaces\n\nAccept dependencies as interfaces in constructors. This decouples components and makes testing straightforward:\n\n```go\ntype UserStore interface {\n    FindByID(ctx context.Context, id string) (*User, error)\n}\n\ntype UserService struct {\n    store UserStore\n}\n\nfunc NewUserService(store UserStore) *UserService {\n    return &UserService{store: store}\n}\n```\n\nIn tests, pass a mock or stub that satisfies `UserStore` — no real database needed.\n\n## Struct Field Tags\n\nUse field tags for serialization control. Exported fields in serialized structs MUST have field tags:\n\n```go\ntype Order struct {\n    ID        string    `json:\"id\"         db:\"id\"`\n    UserID    string    `json:\"user_id\"    db:\"user_id\"`\n    Total     float64   `json:\"total\"      db:\"total\"`\n    Items     []Item    `json:\"items\"      db:\"-\"`\n    CreatedAt time.Time `json:\"created_at\" db:\"created_at\"`\n    DeletedAt time.Time `json:\"-\"          db:\"deleted_at\"`\n    Internal  string    `json:\"-\"          db:\"-\"`\n}\n```\n\n| Directive               | Meaning                                     |\n| ----------------------- | ------------------------------------------- |\n| `json:\"name\"`           | Field name in JSON output                   |\n| `json:\"name,omitempty\"` | Omit field if zero value                    |\n| `json:\"-\"`              | Always exclude from JSON                    |\n| `json:\",string\"`        | Encode number\u002Fbool as JSON string           |\n| `db:\"column\"`           | Database column mapping (sqlx, etc.)        |\n| `yaml:\"name\"`           | YAML field name                             |\n| `xml:\"name,attr\"`       | XML attribute                               |\n| `validate:\"required\"`   | Struct validation (go-playground\u002Fvalidator) |\n\n## Pointer vs Value Receivers\n\n| Use pointer `(s *Server)` | Use value `(s Server)` |\n| --- | --- |\n| Method modifies the receiver | Receiver is small and immutable |\n| Receiver contains `sync.Mutex` or similar | Receiver is a basic type (int, string) |\n| Receiver is a large struct | Method is a read-only accessor |\n| Consistency: if any method uses a pointer, all should | Map and function values (already reference types) |\n\nReceiver type MUST be consistent across all methods of a type — if one method uses a pointer receiver, all methods should.\n\n## Preventing Struct Copies with `noCopy`\n\nSome structs must never be copied after first use (e.g., those containing a mutex, a channel, or internal pointers). Embed a `noCopy` sentinel to make `go vet` catch accidental copies:\n\n```go\n\u002F\u002F noCopy may be added to structs which must not be copied after first use.\n\u002F\u002F See https:\u002F\u002Fpkg.go.dev\u002Fsync#noCopy\ntype noCopy struct{}\n\nfunc (*noCopy) Lock()   {}\nfunc (*noCopy) Unlock() {}\n\ntype ConnPool struct {\n    noCopy noCopy\n    mu     sync.Mutex\n    conns  []*Conn\n}\n```\n\n`go vet` reports an error if a `ConnPool` value is copied (passed by value, assigned, etc.). This is the same technique the standard library uses for `sync.WaitGroup`, `sync.Mutex`, `strings.Builder`, and others.\n\nAlways pass these structs by pointer:\n\n```go\n\u002F\u002F Good\nfunc process(pool *ConnPool) { ... }\n\n\u002F\u002F Bad — go vet will flag this\nfunc process(pool ConnPool) { ... }\n```\n\n## Cross-References\n\n- → See `golang-naming` skill for interface naming conventions (Reader, Closer, Stringer)\n- → See `golang-design-patterns` skill for functional options, constructors, and builder patterns\n- → See `golang-dependency-injection` skill for DI patterns using interfaces\n- → See `golang-code-style` skill for value vs pointer function parameters (distinct from receivers)\n- → See `golang-gopls` skill for safe rename and the `implementInterface` code 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\u002Fsed cannot detect\n\n## Common Mistakes\n\n| Mistake | Fix |\n| --- | --- |\n| Large interfaces (5+ methods) | Split into focused 1-3 method interfaces, compose if needed |\n| Defining interfaces in the implementor package | Define where consumed |\n| Returning interfaces from constructors | Return concrete types |\n| Bare type assertions without comma-ok | Always use `v, ok := x.(T)` |\n| Embedding when you only need a few methods | Use a named field and delegate explicitly |\n| Missing field tags on serialized structs | Tag all exported fields in marshaled types |\n| Mixing pointer and value receivers on a type | Pick one and be consistent |\n| Forgetting compile-time interface check | Add `var _ Interface = (*Type)(nil)` |\n| Using `ToString()` instead of `String()` | Honor canonical method names |\n| Premature interface with a single implementation | Start concrete, extract interface when needed |\n| Nil map\u002Fslice in zero value struct | Use lazy initialization in methods |\n| Using `any` for type-safe operations | Use generics (`[T comparable]`) instead |\n","**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.\n\n> **Community default.** A company skill that explicitly supersedes `golang-structs-interfaces` skill takes precedence.\n\n# Go Structs & Interfaces\n\n## Interface Design Principles\n\n### Keep Interfaces Small\n\n> \"The bigger the interface, the weaker the abstraction.\" — Go Proverbs\n\nInterfaces 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:\n\n→ See `golang-naming` skill for interface naming conventions (method + \"-er\" suffix, canonical names)\n\n```go\ntype Reader interface {\n    Read(p []byte) (n int, err error)\n}\n\ntype Writer interface {\n    Write(p []byte) (n int, err error)\n}\n\n\u002F\u002F Composed from small interfaces\ntype ReadWriter interface {\n    Reader\n    Writer\n}\n```\n\nCompose larger interfaces from smaller ones:\n\n```go\ntype ReadWriteCloser interface {\n    io.Reader\n    io.Writer\n    io.Closer\n}\n```\n\n### Define Interfaces Where They're Consumed\n\nInterfaces Belong to Consumers.\n\nInterfaces 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.\n\n```go\n\u002F\u002F package notification — defines only what it needs\ntype Sender interface {\n    Send(to, body string) error\n}\n\ntype Service struct {\n    sender Sender\n}\n```\n\nThe `email` package exports a concrete `Client` struct — it doesn't need to know about `Sender`.\n\n### Accept Interfaces, Return Structs\n\nFunctions 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.\n\n```go\n\u002F\u002F Good — accepts interface, returns concrete\nfunc NewService(store UserStore) *Service { ... }\n\n\u002F\u002F BAD — NEVER return interfaces from constructors\nfunc NewService(store UserStore) ServiceInterface { ... }\n```\n\n### Don't Create Interfaces Prematurely\n\n> \"Don't design with interfaces, discover them.\"\n\nNEVER create interfaces prematurely — wait for 2+ implementations or a testability requirement. Premature interfaces add indirection without value. Start with concrete types; extract an interface when a second consumer or a test mock demands it.\n\n```go\n\u002F\u002F Bad — premature interface with a single implementation\ntype UserRepository interface {\n    FindByID(ctx context.Context, id string) (*User, error)\n}\ntype userRepository struct { db *sql.DB }\n\n\u002F\u002F Good — start concrete, extract an interface later when needed\ntype UserRepository struct { db *sql.DB }\n```\n\n## Make the Zero Value Useful\n\nDesign structs so they work without explicit initialization. A well-designed zero value reduces constructor boilerplate and prevents nil-related bugs:\n\n```go\n\u002F\u002F Good — zero value is ready to use\nvar buf bytes.Buffer\nbuf.WriteString(\"hello\")\n\nvar mu sync.Mutex\nmu.Lock()\n\n\u002F\u002F Bad — zero value is broken, requires constructor\ntype Registry struct {\n    items map[string]Item \u002F\u002F nil map, panics on write\n}\n\n\u002F\u002F Good — lazy initialization guards the zero value\nfunc (r *Registry) Register(name string, item Item) {\n    if r.items == nil {\n        r.items = make(map[string]Item)\n    }\n    r.items[name] = item\n}\n```\n\n## Avoid `any` \u002F `interface{}` When a Specific Type Will Do\n\nSince 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):\n\n```go\n\u002F\u002F Bad — loses type safety\nfunc Contains(slice []any, target any) bool { ... }\n\n\u002F\u002F Good — generic, type-safe\nfunc Contains[T comparable](slice []T, target T) bool { ... }\n```\n\n## Key Standard Library Interfaces\n\n| Interface     | Package         | Method                                |\n| ------------- | --------------- | ------------------------------------- |\n| `Reader`      | `io`            | `Read(p []byte) (n int, err error)`   |\n| `Writer`      | `io`            | `Write(p []byte) (n int, err error)`  |\n| `Closer`      | `io`            | `Close() error`                       |\n| `Stringer`    | `fmt`           | `String() string`                     |\n| `error`       | builtin         | `Error() string`                      |\n| `Handler`     | `net\u002Fhttp`      | `ServeHTTP(ResponseWriter, *Request)` |\n| `Marshaler`   | `encoding\u002Fjson` | `MarshalJSON() ([]byte, error)`       |\n| `Unmarshaler` | `encoding\u002Fjson` | `UnmarshalJSON([]byte) error`         |\n\nCanonical method signatures MUST be honored — if your type has a `String()` method, it must match `fmt.Stringer`. Don't invent `ToString()` or `ReadData()`.\n\n## Compile-Time Interface Check\n\nVerify a type implements an interface at compile time with a blank identifier assignment. Place it near the type definition:\n\n```go\nvar _ io.ReadWriter = (*MyBuffer)(nil)\n```\n\nThis costs nothing at runtime. If `MyBuffer` ever stops satisfying `io.ReadWriter`, the build fails immediately.\n\n## Type Assertions & Type Switches\n\n### Safe Type Assertion\n\nType assertions MUST use the comma-ok form to avoid panics:\n\n```go\n\u002F\u002F Good — safe\ns, ok := val.(string)\nif !ok {\n    \u002F\u002F handle\n}\n\n\u002F\u002F Bad — panics if val is not a string\ns := val.(string)\n```\n\n### Type Switch\n\nDiscover the dynamic type of an interface value:\n\n```go\nswitch v := val.(type) {\ncase string:\n    fmt.Println(v)\ncase int:\n    fmt.Println(v * 2)\ncase io.Reader:\n    io.Copy(os.Stdout, v)\ndefault:\n    fmt.Printf(\"unexpected type %T\\n\", v)\n}\n```\n\n### Optional Behavior with Type Assertions\n\nCheck if a value supports additional capabilities without requiring them upfront:\n\n```go\ntype Flusher interface {\n    Flush() error\n}\n\nfunc writeData(w io.Writer, data []byte) error {\n    if _, err := w.Write(data); err != nil {\n        return err\n    }\n    \u002F\u002F Flush only if the writer supports it\n    if f, ok := w.(Flusher); ok {\n        return f.Flush()\n    }\n    return nil\n}\n```\n\nThis pattern is used extensively in the standard library (e.g., `http.Flusher`, `io.ReaderFrom`).\n\n## Struct & Interface Embedding\n\n### Struct Embedding\n\nEmbedding promotes the inner type's methods and fields to the outer type — composition, not inheritance:\n\n```go\ntype Logger struct {\n    *slog.Logger\n}\n\ntype Server struct {\n    Logger\n    addr string\n}\n\n\u002F\u002F s.Info(...) works — promoted from slog.Logger through Logger\ns := Server{Logger: Logger{slog.Default()}, addr: \":8080\"}\ns.Info(\"starting\", \"addr\", s.addr)\n```\n\nThe 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.\n\n### When to Embed vs Named Field\n\n| Use | When |\n| --- | --- |\n| **Embed** | You want to promote the full API of the inner type — the outer type \"is a\" enhanced version |\n| **Named field** | You only need the inner type internally — the outer type \"has a\" dependency |\n\n```go\n\u002F\u002F Embed — Server exposes all http.Handler methods\ntype Server struct {\n    http.Handler\n}\n\n\u002F\u002F Named field — Server uses the store but doesn't expose its methods\ntype Server struct {\n    store *DataStore\n}\n```\n\n## Dependency Injection via Interfaces\n\nAccept dependencies as interfaces in constructors. This decouples components and makes testing straightforward:\n\n```go\ntype UserStore interface {\n    FindByID(ctx context.Context, id string) (*User, error)\n}\n\ntype UserService struct {\n    store UserStore\n}\n\nfunc NewUserService(store UserStore) *UserService {\n    return &UserService{store: store}\n}\n```\n\nIn tests, pass a mock or stub that satisfies `UserStore` — no real database needed.\n\n## Struct Field Tags\n\nUse field tags for serialization control. Exported fields in serialized structs MUST have field tags:\n\n```go\ntype Order struct {\n    ID        string    `json:\"id\"         db:\"id\"`\n    UserID    string    `json:\"user_id\"    db:\"user_id\"`\n    Total     float64   `json:\"total\"      db:\"total\"`\n    Items     []Item    `json:\"items\"      db:\"-\"`\n    CreatedAt time.Time `json:\"created_at\" db:\"created_at\"`\n    DeletedAt time.Time `json:\"-\"          db:\"deleted_at\"`\n    Internal  string    `json:\"-\"          db:\"-\"`\n}\n```\n\n| Directive               | Meaning                                     |\n| ----------------------- | ------------------------------------------- |\n| `json:\"name\"`           | Field name in JSON output                   |\n| `json:\"name,omitempty\"` | Omit field if zero value                    |\n| `json:\"-\"`              | Always exclude from JSON                    |\n| `json:\",string\"`        | Encode number\u002Fbool as JSON string           |\n| `db:\"column\"`           | Database column mapping (sqlx, etc.)        |\n| `yaml:\"name\"`           | YAML field name                             |\n| `xml:\"name,attr\"`       | XML attribute                               |\n| `validate:\"required\"`   | Struct validation (go-playground\u002Fvalidator) |\n\n## Pointer vs Value Receivers\n\n| Use pointer `(s *Server)` | Use value `(s Server)` |\n| --- | --- |\n| Method modifies the receiver | Receiver is small and immutable |\n| Receiver contains `sync.Mutex` or similar | Receiver is a basic type (int, string) |\n| Receiver is a large struct | Method is a read-only accessor |\n| Consistency: if any method uses a pointer, all should | Map and function values (already reference types) |\n\nReceiver type MUST be consistent across all methods of a type — if one method uses a pointer receiver, all methods should.\n\n## Preventing Struct Copies with `noCopy`\n\nSome structs must never be copied after first use (e.g., those containing a mutex, a channel, or internal pointers). Embed a `noCopy` sentinel to make `go vet` catch accidental copies:\n\n```go\n\u002F\u002F noCopy may be added to structs which must not be copied after first use.\n\u002F\u002F See https:\u002F\u002Fpkg.go.dev\u002Fsync#noCopy\ntype noCopy struct{}\n\nfunc (*noCopy) Lock()   {}\nfunc (*noCopy) Unlock() {}\n\ntype ConnPool struct {\n    noCopy noCopy\n    mu     sync.Mutex\n    conns  []*Conn\n}\n```\n\n`go vet` reports an error if a `ConnPool` value is copied (passed by value, assigned, etc.). This is the same technique the standard library uses for `sync.WaitGroup`, `sync.Mutex`, `strings.Builder`, and others.\n\nAlways pass these structs by pointer:\n\n```go\n\u002F\u002F Good\nfunc process(pool *ConnPool) { ... }\n\n\u002F\u002F Bad — go vet will flag this\nfunc process(pool ConnPool) { ... }\n```\n\n## Cross-References\n\n- → See `golang-naming` skill for interface naming conventions (Reader, Closer, Stringer)\n- → See `golang-design-patterns` skill for functional options, constructors, and builder patterns\n- → See `golang-dependency-injection` skill for DI patterns using interfaces\n- → See `golang-code-style` skill for value vs pointer function parameters (distinct from receivers)\n- → See `golang-gopls` skill for safe rename and the `implementInterface` code 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\u002Fsed cannot detect\n\n## Common Mistakes\n\n| Mistake | Fix |\n| --- | --- |\n| Large interfaces (5+ methods) | Split into focused 1-3 method interfaces, compose if needed |\n| Defining interfaces in the implementor package | Define where consumed |\n| Returning interfaces from constructors | Return concrete types |\n| Bare type assertions without comma-ok | Always use `v, ok := x.(T)` |\n| Embedding when you only need a few methods | Use a named field and delegate explicitly |\n| Missing field tags on serialized structs | Tag all exported fields in marshaled types |\n| Mixing pointer and value receivers on a type | Pick one and be consistent |\n| Forgetting compile-time interface check | Add `var _ Interface = (*Type)(nil)` |\n| Using `ToString()` instead of `String()` | Honor canonical method names |\n| Premature interface with a single implementation | Start concrete, extract interface when needed |\n| Nil map\u002Fslice in zero value struct | Use lazy initialization in methods |\n| Using `any` for type-safe operations | Use generics (`[T comparable]`) instead |\n",{"name":5,"paths":44,"license":15,"metadata":46,"description":7,"allowed-tools":56,"compatibility":57,"user-invocable":58},[45],"**\u002F*.go",{"author":47,"version":48,"openclaw":49},"samber","1.2.0",{"emoji":50,"install":51,"homepage":52,"requires":53},"?",[],"https:\u002F\u002Fgithub.com\u002Fsamber\u002Fcc-skills-golang",{"bins":54},[55],"go","Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent AskUserQuestion","Designed for Claude Code, Codex or similar harness, and for projects using Golang.",true,"main","c349be0704bffe54a7191d1412faf564b08983ca","skills\u002Fsamber-golang\u002Fgolang-structs-interfaces",0,"https:\u002F\u002Fgithub.com\u002Frockcookies\u002Fskills","https:\u002F\u002Fgithub.com\u002Frockcookies","2026-11-12 14:42:52",{"source":8,"skillName":5,"commands":67,"prompt":77,"zipAvailable":58},[68,71,74],{"tool":69,"command":70},"npx","npx skills add rockcookies\u002Fskills --skill golang-structs-interfaces",{"tool":72,"command":73},"bunx","bunx skills add rockcookies\u002Fskills --skill golang-structs-interfaces",{"tool":75,"command":76},"pnpm","pnpm dlx skills add rockcookies\u002Fskills --skill golang-structs-interfaces","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Frockcookies\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fsamber-golang\u002Fgolang-structs-interfaces\u002FSKILL.md",[79,85,89,93,97,101,105,109,113,117,121],{"path":80,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":83,"sourceHtmlUrl":84},"evals\u002Fevals.json","REFERENCE","参考文档",13585,"https:\u002F\u002Fgithub.com\u002Frockcookies\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fsamber-golang\u002Fgolang-structs-interfaces\u002Fevals\u002Fevals.json",{"path":86,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":87,"sourceHtmlUrl":88},"references\u002Fconcurrency.md",5251,"https:\u002F\u002Fgithub.com\u002Fcompozy\u002Fcompozy\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgolang-master\u002Freferences\u002Fconcurrency.md",{"path":90,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":91,"sourceHtmlUrl":92},"references\u002Fcontext.md",3666,"https:\u002F\u002Fgithub.com\u002Fcompozy\u002Fcompozy\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgolang-master\u002Freferences\u002Fcontext.md",{"path":94,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":95,"sourceHtmlUrl":96},"references\u002Ferrors.md",4719,"https:\u002F\u002Fgithub.com\u002Fcompozy\u002Fcompozy\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgolang-master\u002Freferences\u002Ferrors.md",{"path":98,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":99,"sourceHtmlUrl":100},"references\u002Finterfaces-generics.md",5396,"https:\u002F\u002Fgithub.com\u002Fcompozy\u002Fcompozy\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgolang-master\u002Freferences\u002Finterfaces-generics.md",{"path":102,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":103,"sourceHtmlUrl":104},"references\u002Flayout.md",2692,"https:\u002F\u002Fgithub.com\u002Fcompozy\u002Fcompozy\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgolang-master\u002Freferences\u002Flayout.md",{"path":106,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":107,"sourceHtmlUrl":108},"references\u002Fmodernize.md",2993,"https:\u002F\u002Fgithub.com\u002Fcompozy\u002Fcompozy\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgolang-master\u002Freferences\u002Fmodernize.md",{"path":110,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":111,"sourceHtmlUrl":112},"references\u002Fperformance.md",4621,"https:\u002F\u002Fgithub.com\u002Fcompozy\u002Fcompozy\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgolang-master\u002Freferences\u002Fperformance.md",{"path":114,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":115,"sourceHtmlUrl":116},"references\u002Fsafety.md",5157,"https:\u002F\u002Fgithub.com\u002Fcompozy\u002Fcompozy\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgolang-master\u002Freferences\u002Fsafety.md",{"path":118,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":119,"sourceHtmlUrl":120},"references\u002Fstyle-naming.md",5639,"https:\u002F\u002Fgithub.com\u002Fcompozy\u002Fcompozy\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgolang-master\u002Freferences\u002Fstyle-naming.md",{"path":122,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":123,"sourceHtmlUrl":124},"references\u002Ftesting.md",5183,"https:\u002F\u002Fgithub.com\u002Fcompozy\u002Fcompozy\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fgolang-master\u002Freferences\u002Ftesting.md",[126,157,181,202,228,243],{"skillNo":127,"name":128,"nameZh":129,"description":130,"descriptionZh":131,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":132,"sourceHtmlUrl":133,"categories":134,"keywords":145,"publishedAt":156},"01M6CFPKHRH0GD3W2GTGWE9WGP","kami","Kami 专业文档排版","Typeset professional documents with Kami templates: resumes, one-pagers, white papers, letters, portfolios, and slide decks. Use when asked to 做 PDF \u002F 排版 \u002F 简历 \u002F 一页纸 \u002F PPT \u002F slides, or to create a Kami landing page. Not for auditing or restyling an existing product site.","使用 Kami 模板排版专业文档：简历、一页纸、白皮书、信件、作品集和幻灯片。当用户要求做 PDF \u002F 排版 \u002F 简历 \u002F 一页纸 \u002F PPT \u002F slides，或创建 Kami 落地页时使用。不适用于审查或重新设计现有产品网站。","https:\u002F\u002Fgithub.com\u002Frockcookies\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Ftw93-kami\u002Fkami\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Frockcookies\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Ftw93-kami\u002Fkami\u002FSKILL.md",[135,140],{"categoryNo":136,"categoryName":137,"taxonomyType":138,"taxonomyTypeDesc":139},"01M8BQ6TK1MPB82068236GSXDE","文档处理","SCENARIO","使用场景",{"categoryNo":141,"categoryName":142,"taxonomyType":143,"taxonomyTypeDesc":144},"01M8C55A3R2M9C8CAKG3W16HTA","内容创作者","PROFESSION","适用职业",[128,146,147,148,149,150,151,152,153,154,24,155],"create","PDF","pptx","slides","product","page","landing","templates","site","documents","2026-11-12 13:55:43",{"skillNo":158,"name":159,"nameZh":6,"description":160,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":161,"categories":162,"keywords":163,"publishedAt":39},"01M6WMNKD3Y4H9FGM8Q901F507","hierarchical-agents-md","层级 AGENTS.md \u002F README.md：init、update、audit、reorganize、trim。 初始化 Agent 指令、代码改动后同步文档、检查文档漂移、重组仓库文档层级、精简规则与 Skills。 Not for 写业务代码或生成文档站点。","https:\u002F\u002Fgithub.com\u002Frockcookies\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fcustom\u002Fhierarchical-agents-md\u002FSKILL.md",[],[164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180],"hierarchical agents md","agents md","packages","change","maintenance","初始化","audit","for","README","update","python","init","git","true","party","third-party","文档",{"skillNo":182,"name":183,"nameZh":184,"description":185,"descriptionZh":186,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":187,"categories":188,"keywords":195,"publishedAt":39},"01M6CFS6BRTQPFZCDHQP97HYXR","vueuse-functions","VueUse 组合式函数应用","Apply VueUse composables where appropriate to build concise, maintainable Vue.js \u002F Nuxt features.","在合适的地方应用 VueUse 组合式函数（composables），以构建简洁、可维护的 Vue.js \u002F Nuxt 功能。","https:\u002F\u002Fgithub.com\u002Frockcookies\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fvueuse\u002Fvueuse-functions\u002FSKILL.md",[189,192],{"categoryNo":190,"categoryName":191,"taxonomyType":143,"taxonomyTypeDesc":144},"01M8BQ6TQZN6R52WBJ9H8NRMQM","软件开发工程师",{"categoryNo":193,"categoryName":194,"taxonomyType":138,"taxonomyTypeDesc":139},"01M8BRASNPVNJVQQJ4KZX8XM5D","前端开发与界面实现",[196,197,198,31,199,200,37,201],"vueuse functions","functions","nuxt","vue","build","js",{"skillNo":203,"name":204,"nameZh":205,"description":206,"descriptionZh":207,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":208,"categories":209,"keywords":216,"publishedAt":39},"01M6CFS34MDQXZPAWQFE5D7VGT","vue-testing-best-practices","Vue.js 测试最佳实践","Use for Vue.js testing. Covers Vitest, Vue Test Utils, component testing, mocking, testing patterns, and Playwright for E2E testing.","用于 Vue.js 测试。涵盖 Vitest、Vue Test Utils、组件测试、模拟（mocking）、测试模式，以及用于 E2E 测试的 Playwright。","https:\u002F\u002Fgithub.com\u002Frockcookies\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fvuejs-ai\u002Fvue-testing-best-practices\u002FSKILL.md",[210,213],{"categoryNo":211,"categoryName":212,"taxonomyType":143,"taxonomyTypeDesc":144},"01M8BQGD5WG86P4AQ5GPSSKBFR","测试工程师",{"categoryNo":214,"categoryName":215,"taxonomyType":138,"taxonomyTypeDesc":139},"01M8BQJH394GT47X57A9Q8G7HX","测试与质量保障",[217,218,219,199,220,201,221,222,24,223,224,225,37,226,227],"vue testing best practices","testing","testing best practices","best practices","e2e testing","playwright","test","testing patterns","component","vitest","e2e",{"skillNo":229,"name":230,"nameZh":231,"description":232,"descriptionZh":233,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":234,"categories":235,"keywords":238,"publishedAt":39},"01M6CFS0N19MSJNTVM9AEQ7Z73","vue-router-best-practices","Vue Router 路由最佳实践","Vue Router 4 patterns, navigation guards, route params, and route-component lifecycle interactions.","Vue Router 4 模式、导航守卫、路由参数以及路由与组件生命周期的交互。","https:\u002F\u002Fgithub.com\u002Frockcookies\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fvuejs-ai\u002Fvue-router-best-practices\u002FSKILL.md",[236,237],{"categoryNo":190,"categoryName":191,"taxonomyType":143,"taxonomyTypeDesc":144},{"categoryNo":193,"categoryName":194,"taxonomyType":138,"taxonomyTypeDesc":139},[220,239,199,240,225,37,241,242],"vue router best practices","router","navigation","lifecycle",{"skillNo":244,"name":245,"nameZh":246,"description":247,"descriptionZh":248,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":249,"categories":250,"keywords":253,"publishedAt":39},"01M6CFRYN31RFQFTE41Z6DCGKE","vue-pinia-best-practices","Pinia 状态管理最佳实践","Pinia stores, state management patterns, store setup, and reactivity with stores.","Pinia store、状态管理模式、store 配置以及 store 的响应式处理。","https:\u002F\u002Fgithub.com\u002Frockcookies\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fvuejs-ai\u002Fvue-pinia-best-practices\u002FSKILL.md",[251,252],{"categoryNo":190,"categoryName":191,"taxonomyType":143,"taxonomyTypeDesc":144},{"categoryNo":193,"categoryName":194,"taxonomyType":138,"taxonomyTypeDesc":139},[254,220,199,255,37,256,257,258,259],"vue pinia best practices","pinia","state","state management","management","setup"]