GO Go

Go: Structs & Interfaces

What you will learn

Go has no classes. Instead, structs group data and interfaces define behavior. Unlike Java, interfaces are satisfied implicitly.

Structs — data containers

type Person struct {
    Name string
    Age  int
}

// Create instances
p1 := Person{Name: "Alice", Age: 25}
p2 := Person{"Bob", 30}  // positional — fragile, avoid

fmt.Println(p1.Name)  // dot notation
p1.Age = 26           // fields are mutable

Methods on structs

Methods are functions with a receiver — the type they belong to:

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

// Pointer receiver (can modify)
func (p *Person) Birthday() {
    p.Age++
}

alice := Person{Name: "Alice", Age: 25}
fmt.Println(alice.Greet())  // Hi, I'm Alice
alice.Birthday()
fmt.Println(alice.Age)      // 26

Pointer receiver (*Person) lets the method modify the struct. Value receiver (Person) works on a copy.

Interfaces — implicit satisfaction

An interface defines a set of methods. Any type that implements those methods satisfies the interface automatically — no implements keyword needed:

type Greeter interface {
    Greet() string
}

// Person already has Greet(), so it satisfies Greeter implicitly
var g Greeter = Person{Name: "Alice"}
fmt.Println(g.Greet())  // Hi, I'm Alice

This is duck typing at compile time: "If it walks like a duck and quacks like a duck, it's a duck."

Quick check below!