Structs, Methods & Interfaces¶
Python's class maps to Go's struct + methods + interfaces. Go has no inheritance — it uses composition instead.
Class Definition¶
Constructor¶
Instance Method¶
type Counter struct {
count int
}
// Pointer receiver: can modify the struct's fields
func (c *Counter) Increment() {
c.count++
}
Value receiver vs Pointer receiver
A value receiver func (c Counter) operates on a copy — modifications won't
be reflected on the original struct. Use a pointer receiver func (c *Counter)
when you need to mutate state.
classmethod / staticmethod¶
Private / Public¶
type Account struct {
Owner string // Uppercase = exported (public)
balance float64 // lowercase = unexported (private)
}
func (a Account) Balance() float64 {
return a.balance
}
Capitalization determines visibility
Go has one simple rule: Uppercase = exported (accessible from other packages), lowercase = unexported. This applies to struct fields, methods, functions, variables, and constants.
ABC / Abstract¶
type Shape interface {
Area() float64
}
type Circle struct {
Radius float64
}
// Circle automatically satisfies the Shape interface
func (c Circle) Area() float64 {
return 3.14159 * c.Radius * c.Radius
}
Interfaces are implicit
Go does not require implements Shape. As long as a struct implements all methods
of an interface, it automatically satisfies it. This is called structural typing.
Inheritance¶
// Go has no inheritance — use struct embedding (composition)
type Animal struct {
Name string
}
func (a Animal) Speak() string {
return "..."
}
type Dog struct {
Animal // embedding: Dog gets Animal's fields and methods
}
// Override Speak
func (d Dog) Speak() string {
return fmt.Sprintf("%s says Woof!", d.Name)
}
dog := Dog{Animal{Name: "Rex"}}
dog.Name // access embedded field directly
dog.Speak() // "Rex says Woof!"