Structs, Methods and Interfaces

Harry · 14 Sep 2026 · 1 views
Advertisement
Advertisement

Structs group data

Go has no classes. Instead you compose data into a struct:

type Person struct {
    Name string
    Age  int
}

p := Person{Name: "Ada", Age: 36}
fmt.Println(p.Name)

Methods

You attach behaviour by declaring a function with a receiver – the type it belongs to:

func (p Person) Greet() string {
    return "Hi, I am " + p.Name
}

// pointer receiver to modify the struct
func (p *Person) Birthday() {
    p.Age++
}

Use a pointer receiver (*Person) when the method needs to change the struct; a value receiver gets a copy.

Interfaces: behaviour, not hierarchy

An interface lists methods. Any type that has those methods satisfies the interface automatically – there is no implements keyword. This “structural” typing keeps code loosely coupled:

type Shape interface {
    Area() float64
}

type Circle struct { R float64 }
func (c Circle) Area() float64 { return 3.14159 * c.R * c.R }

// Circle satisfies Shape simply by having Area()
func describe(s Shape) {
    fmt.Println("area:", s.Area())
}

Why it matters

Because interfaces are satisfied implicitly, you can write functions against small interfaces and pass any matching type – including types from libraries you do not control. This is Go's main tool for decoupling and testing (pass a fake that satisfies the interface).

Key points

  • Structs group related data; Go has no classes.
  • Methods attach to a type via a receiver; use pointer receivers to mutate.
  • Interfaces list methods and are satisfied implicitly – no implements.
  • Small interfaces make code decoupled and easy to test.
Share this post:

Comments (0)

Please login or register to comment.