Structs and methods
Go has no classes. Instead, you define data with structs and attach behaviour to any type with methods. Code reuse comes from embedding one struct in another rather than inheritance. It's a smaller toolbox than Java's or Python's, and that's deliberate.
Structs
package main
import "fmt"
type Product struct {
Name string
PriceCents int
Stock int
Tags []string
}
func main() {
p := Product{Name: "Keyboard", PriceCents: 4950, Stock: 12}
p.Stock -= 2
p.Tags = append(p.Tags, "office")
fmt.Println(p.Name, p.Stock)
fmt.Printf("%v\n%+v\n", p, p)
var empty Product // all fields at their zero values
fmt.Printf("%+v\n", empty)
point := struct{ X, Y int }{3, 4} // an anonymous struct, handy for one-offs
fmt.Println(point)
}Keyboard 10
{Keyboard 4950 10 [office]}
{Name:Keyboard PriceCents:4950 Stock:10 Tags:[office]}
{Name: PriceCents:0 Stock:0 Tags:[]}
{3 4}- Name the fields when you create a struct (
Name: "Keyboard"). Any field you leave out gets its zero value. %+vprints field names, which makes it the best verb for debugging.- Capitalised fields (
Name) are exported: visible outside the package and toencoding/json. Lowercase fields are private to the package.
Structs are values: assigning or passing one copies all its fields.
package main
import "fmt"
type Point struct{ X, Y int }
func main() {
a := Point{1, 2}
b := a // a copy
b.X = 100
fmt.Println(a, b)
pa := &a // a pointer to a
pa.X = 50 // Go follows the pointer automatically (no -> needed)
fmt.Println(a, a == Point{50, 2})
}{1 2} {100 2}
{50 2} trueMethods
A method is a function with a receiver, written before its name:
package main
import (
"fmt"
"math"
)
type Rect struct{ W, H float64 }
type Circle struct{ R float64 }
func (r Rect) Area() float64 { return r.W * r.H }
func (r Rect) Perimeter() float64 { return 2 * (r.W + r.H) }
func (c Circle) Area() float64 { return math.Pi * c.R * c.R }
func main() {
r := Rect{W: 3, H: 4}
c := Circle{R: 1}
fmt.Println(r.Area(), r.Perimeter())
fmt.Printf("%.4f\n", c.Area())
}12 14 3.1416
You can add methods to any type you define in your package, not just structs: type Celsius float64 can have a func (c Celsius) String() string.
Pointer receivers
A method with a value receiver (r Rect) gets a copy. To change the struct, use a pointer receiver (a *Account):
package main
import (
"errors"
"fmt"
)
type Account struct {
Owner string
balance int // lowercase: only this package can touch it directly
}
func (a *Account) Deposit(amount int) {
a.balance += amount
}
func (a *Account) Withdraw(amount int) error {
if amount > a.balance {
return errors.New("insufficient funds")
}
a.balance -= amount
return nil
}
func (a *Account) Balance() int { return a.balance }
func main() {
acc := Account{Owner: "Asha"}
acc.Deposit(100) // Go takes &acc for you
if err := acc.Withdraw(250); err != nil {
fmt.Println("withdraw failed:", err)
}
_ = acc.Withdraw(30)
fmt.Println(acc.Owner, acc.Balance())
}withdraw failed: insufficient funds Asha 70
When to use which:
- Pointer receiver if the method changes the struct, or the struct is large (copying is wasteful), or it contains something that must not be copied (like a
sync.Mutex). - Value receiver for small, read-only types (
Point,Rect,time.Time). - Be consistent: if any method needs a pointer receiver, give them all one.
Constructors
Go has no constructors. By convention, a function named NewThing creates and validates a Thing:
package main
import (
"fmt"
"strings"
)
type User struct {
Email string
Name string
Roles []string
}
func NewUser(email, name string) (*User, error) {
email = strings.ToLower(strings.TrimSpace(email))
if !strings.Contains(email, "@") {
return nil, fmt.Errorf("invalid email %q", email)
}
return &User{Email: email, Name: name, Roles: []string{"viewer"}}, nil
}
func (u *User) IsAdmin() bool {
for _, r := range u.Roles {
if r == "admin" {
return true
}
}
return false
}
func main() {
u, err := NewUser(" Asha@Example.COM ", "Asha")
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%+v admin=%v\n", *u, u.IsAdmin())
if _, err := NewUser("nope", "X"); err != nil {
fmt.Println("error:", err)
}
}{Email:asha@example.com Name:Asha Roles:[viewer]} admin=false
error: invalid email "nope"Returning &User{…} is safe in Go: the compiler notices the value outlives the function and puts it on the heap, and the garbage collector frees it later.
Embedding instead of inheritance
Embedding a type inside a struct makes its fields and methods available directly on the outer struct:
package main
import (
"fmt"
"time"
)
type Timestamps struct {
CreatedAt time.Time
UpdatedAt time.Time
}
func (t *Timestamps) Touch(now time.Time) { t.UpdatedAt = now }
type Order struct {
Timestamps // embedded: no field name
ID int
Total int
}
func main() {
start := time.Date(2026, 11, 22, 10, 0, 0, 0, time.UTC)
o := Order{ID: 7, Total: 2599, Timestamps: Timestamps{CreatedAt: start, UpdatedAt: start}}
o.Touch(start.Add(90 * time.Minute)) // promoted method
fmt.Println(o.ID, o.CreatedAt.Format(time.Kitchen), o.UpdatedAt.Format(time.Kitchen))
fmt.Println(o.Timestamps.UpdatedAt.Sub(o.CreatedAt))
}7 10:00AM 11:30AM 1h30m0s
This is composition: an Order has timestamps, rather than being a kind of Timestamps. You get the reuse without the deep class hierarchies that make inheritance-heavy code hard to change.
Struct tags and JSON
Struct fields can carry tags: metadata that packages like encoding/json read to control how fields are encoded:
package main
import (
"encoding/json"
"fmt"
)
type Item struct {
ID int `json:"id"`
Name string `json:"name"`
Price float64 `json:"price"`
Tags []string `json:"tags,omitempty"`
internal string // unexported: never encoded
}
func main() {
it := Item{ID: 1, Name: "Mouse", Price: 19.99, internal: "secret"}
data, err := json.Marshal(it)
if err != nil {
panic(err)
}
fmt.Println(string(data))
var decoded []Item
input := `[{"id":2,"name":"Monitor","price":229,"tags":["4k","27in"]},{"id":3,"name":"Cable","price":5.5}]`
if err := json.Unmarshal([]byte(input), &decoded); err != nil {
panic(err)
}
fmt.Printf("%+v\n", decoded)
pretty, _ := json.MarshalIndent(decoded[0], "", " ")
fmt.Println(string(pretty))
}{"id":1,"name":"Mouse","price":19.99}
[{ID:2 Name:Monitor Price:229 Tags:[4k 27in] internal:} {ID:3 Name:Cable Price:5.5 Tags:[] internal:}]
{
"id": 2,
"name": "Monitor",
"price": 229,
"tags": [
"4k",
"27in"
]
}json:"name"sets the JSON key;omitemptyleaves out empty values.- Only exported fields are encoded.
Unmarshalneeds a pointer (&decoded) so it can fill the value in.
The String() method
If a type has a String() string method, fmt uses it whenever the value is printed:
package main
import "fmt"
type Money int64 // in cents
func (m Money) String() string {
return fmt.Sprintf("₹%d.%02d", m/100, m%100)
}
func main() {
price := Money(123456)
fmt.Println("total:", price)
fmt.Printf("%v and %d\n", price, price)
}total: ₹1234.56 ₹1234.56 and 123456
That's your first taste of interfaces: fmt doesn't know about Money, but it knows how to print anything with a String() method. That's the next lesson.
Practice
- Define
type Book structwith title, author and year, and a methodAge(now int) int. - Write a
Stacktype withPush,Pop(returning a value and a bool) andLenmethods, using a slice inside. - Embed an
Addressstruct in aCustomerand access the city directly asc.City. - Encode a slice of your
Books to indented JSON, then decode it back.
1.When should a method have a pointer receiver?
2.Which struct fields does encoding/json include?
3.How does Go reuse code between types instead of inheritance?
4.What does b := a do when a is a struct?