How to Use Anonymous Field in Struct in Go: Simple Guide
In Go, you use an
anonymous field in a struct by declaring a field with only the type name and no explicit field name. This embeds the type directly, allowing you to access its fields and methods as if they belong to the outer struct.Syntax
An anonymous field in a Go struct is declared by specifying only the type name without a field name. This embeds the type into the struct.
Example syntax:
type Outer struct {
InnerType
}Here, InnerType is embedded anonymously inside Outer. You can access InnerType's fields directly from Outer.
go
type Inner struct { Name string } type Outer struct { Inner }
Example
This example shows how to embed a struct anonymously and access its fields directly from the outer struct.
go
package main import "fmt" type Address struct { City string State string } type Person struct { Name string Address // anonymous field } func main() { p := Person{ Name: "Alice", Address: Address{ City: "Seattle", State: "WA", }, } // Access embedded fields directly fmt.Println(p.Name) // Alice fmt.Println(p.City) // Seattle fmt.Println(p.State) // WA }
Output
Alice
Seattle
WA
Common Pitfalls
Common mistakes when using anonymous fields include:
- Embedding pointer vs value types without understanding how it affects method calls and memory.
- Field name conflicts when multiple anonymous fields have the same field names.
- Assuming anonymous fields are inherited like in other languages; Go uses embedding, not inheritance.
Example of field name conflict:
go
package main import "fmt" type A struct { Name string } type B struct { Name string } type C struct { A // anonymous field B // anonymous field } func main() { c := C{ A: A{Name: "From A"}, B: B{Name: "From B"}, } // fmt.Println(c.Name) // Error: ambiguous selector fmt.Println(c.A.Name) // Correct access fmt.Println(c.B.Name) // Correct access }
Output
From A
From B
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Anonymous Field | Embedding a type without a field name | type S struct { T } |
| Access Embedded Fields | Access fields of embedded type directly | s.FieldName |
| Field Name Conflict | Ambiguous if multiple embedded types have same field | Use s.T.FieldName |
| Pointer vs Value | Embedding pointer affects method receivers | type S struct { *T } |
Key Takeaways
Anonymous fields embed a type in a struct without naming the field explicitly.
You can access embedded fields and methods directly from the outer struct.
Be careful of field name conflicts when embedding multiple types with same field names.
Embedding pointers vs values changes how methods and memory behave.
Go embedding is composition, not inheritance.