Structs are Go's primary way to group fields—like classes without inheritance. Compare with struct in C# or plain data classes in Java records.
Defining and using structs
type Person struct {
Name string
Age int
}
p := Person{Name: "Ada", Age: 36}
Struct literals require field names for clarity when omitting fields. Zero value is a struct with zero-valued fields.
Embedding (composition)
Anonymous struct embedding promotes fields and methods—Go favors composition over inheritance. Embedded types must be unexported or exported consistently.
Important interview questions and answers
- Q: Classes in Go?
A: No classes—structs plus methods and interfaces replace OOP hierarchies. - Q: Struct embedding vs inheritance?
A: Embedding composes behavior without subtype polymorphism by default—interfaces provide polymorphism.
Self-check
- How do you create a Person with Name "Ada"?
- What is the zero value of a struct?
Tip: Go favors composition via embedded structs over inheritance—compare with class hierarchies in Java.
Interview prep
- Classes in Go?
No classes—structs with methods and interfaces replace inheritance hierarchies.
- Struct embedding?
Anonymous embedding promotes fields/methods—composition over inheritance.