Struct Types and Methods
Structs are how we create custom data structures in Go. They allow you to group related data together and attach behavior through methods.Composition over Inheritance
Go doesn’t haveclass or extends keywords. Instead of inheritance, Go uses composition - building complex types by combining simpler ones.
Defining Structs
Here’s a real-world example of an Order struct:Creating Instances
There are multiple ways to create struct instances:Constructor Functions
Go doesn’t have formal constructors, but the convention is to createnew functions:
Constructor functions typically return pointers (
*Order) rather than values, making them more efficient for large structs.Methods
Methods are functions with a special receiver argument. They attach behavior to your structs.Method Syntax
(o *Order) comes between func and the method name. This binds the method to the Order type.
Using Methods
Value vs Pointer Receivers
Pointer Receivers (*Order)
Use pointer receivers when you need to:
- Modify the struct’s fields
- Avoid copying large structs
- Maintain consistency (if some methods use pointers, all should)
Value Receivers (Order)
Use value receivers for:
- Small, immutable structs
- Methods that don’t modify state
- When you explicitly want a copy
Exported vs Unexported Fields
Go uses capitalization to control visibility:- Uppercase fields are exported (accessible from other packages)
- Lowercase fields are unexported (private to the package)
Embedded Structs (Composition)
Instead of inheritance, Go uses embedding:Customer struct “has-a” Address rather than “is-a” Address. This is composition.
Struct Tags
Struct tags provide metadata for serialization and validation:encoding/json to control marshaling:
Zero Values
Uninitialized struct fields get their type’s zero value:Best Practices
- Use pointer receivers for methods that modify the struct
- Keep constructors simple - just initialize and return
- Prefer composition over complex struct hierarchies
- Export selectively - only expose what’s necessary
- Use tags for JSON/XML/database mapping
Structs are value types. Assigning one struct to another creates a copy. Use pointers when you want to share the same instance.