Structs, methods and pointers
Course contents (17 lessons)
- Getting started with Go
- Installing Go 1.25 and your first program
- Variables, types and constants
- Control flow: if, for and switch
- Functions, multiple returns and defer
- Slices and maps
- Arrays and slices
- Maps and working with strings
- Structs, methods and interfaces
- Structs, methods and pointers
- Interfaces
- Errors, packages and generics
- Error handling the Go way
- Packages and modules
- Generics
- Concurrency
- Goroutines and channels
- select, timeouts and context
- Mutexes, sync and the race detector
- Testing
- Testing and benchmarks
- Building and shipping a service
- Building an HTTP JSON API with net/http
- Building and deploying a Go service
Go has no classes
Go does not have classes or inheritance. What it has is simpler: a struct groups fields together, and you can attach functions called methods to any type you define. Together they cover most of what people use classes for.
Defining a struct
package main
import (
"fmt"
"strings"
)
type Item struct {
Name string
Price int // in paisa
Quantity int
}
// value receiver: works on a copy, good for read-only methods
func (i Item) Total() int {
return i.Price * i.Quantity
}
type Invoice struct {
Number string
Customer string
Items []Item
}
// constructor function by convention
func NewInvoice(number, customer string) *Invoice {
return &Invoice{Number: number, Customer: customer}
}
// pointer receiver: can change the invoice
func (inv *Invoice) Add(name string, price, qty int) {
inv.Items = append(inv.Items, Item{Name: name, Price: price, Quantity: qty})
}
func (inv Invoice) Total() int {
sum := 0
for _, it := range inv.Items {
sum += it.Total()
}
return sum
}
func (inv Invoice) String() string {
var sb strings.Builder
fmt.Fprintf(&sb, "Invoice %s for %s\n", inv.Number, inv.Customer)
for _, it := range inv.Items {
fmt.Fprintf(&sb, " %-12s %3d x %8.2f\n", it.Name, it.Quantity, float64(it.Price)/100)
}
fmt.Fprintf(&sb, " Total: Rs %.2f", float64(inv.Total())/100)
return sb.String()
}
func main() {
inv := NewInvoice("INV-001", "Ali Traders")
inv.Add("Paper ream", 125050, 4)
inv.Add("Stapler", 48000, 2)
fmt.Println(inv)
line := Item{"Pen", 4000, 10}
fmt.Printf("%+v total %d\n", line, line.Total())
}
Output:
Invoice INV-001 for Ali Traders
Paper ream 4 x 1250.50
Stapler 2 x 480.00
Total: Rs 5962.00
{Name:Pen Price:4000 Quantity:10} total 40000
Methods and receivers
A method is a function with an extra parameter before its name, the receiver. func (i Item) Total() int says: Total is a method of Item, and inside it the item is called i. Go convention is a short name, one or two letters, not this or self.
A value receiver gets a copy of the struct. Changes inside the method do not affect the original. A pointer receiver (*Invoice) gets the address, so the method can modify the real struct and avoids copying large structs. In Add we need a pointer receiver, because we are changing inv.Items. If we had used a value receiver, the append would have changed a copy and the invoice would stay empty. That is the most common receiver mistake.
The rule of thumb I follow: if any method needs a pointer receiver, use pointer receivers for all methods of that type, so the behaviour is consistent. In our example I mixed them to show both. In production code, Invoice would use pointers throughout, since it is a mutable thing with identity.
Pointers in two minutes
A pointer holds the memory address of a value. &x takes the address of x and *p follows a pointer to the value. Go has no pointer arithmetic, so pointers are much safer than in C. You do not need to dereference by hand for field access: inv.Items works for both a struct and a pointer to one. A nil pointer, though, will panic if you use it: invalid memory address or nil pointer dereference.
Constructors
Go has no constructors, so by convention you write a function named NewSomething that returns a ready-to-use value, often a pointer. Use it when the zero value is not usable, or to enforce rules like required fields. Better still, design types so that their zero value works. For example a sync.Mutex or bytes.Buffer is ready to use as it is.
Exported and unexported names
Go has no public or private keywords. A name that starts with a capital letter is exported: visible from other packages. A lowercase name is only visible inside its own package. This applies to types, functions, methods and struct fields. Fields such as Name above are exported. JSON encoding, which we use later, only sees exported fields.
Embedding
You can place one struct inside another without a field name. Its fields and methods are then promoted to the outer type. This is Go's tool for reuse.
type Audit struct {
CreatedBy string
}
func (a Audit) Describe() string { return "created by " + a.CreatedBy }
type Order struct {
Audit // embedded
ID int
}
o := Order{Audit: Audit{CreatedBy: "sara"}, ID: 7}
fmt.Println(o.CreatedBy, o.Describe()) // promoted
This is composition, not inheritance. Order is not an Audit, and you cannot pass an Order where an Audit is required. It simply borrows the fields and methods.
Struct tags
A struct field can have a tag, a string in backticks that libraries read, most often for JSON:
type Product struct {
ID int `json:"id"`
Name string `json:"name"`
Price int `json:"price_paisa"`
Note string `json:"note,omitempty"`
}
Common mistakes
- Value receiver that tries to modify. The change is lost.
- Copying structs that contain a mutex. Copying a struct that includes a
sync.Mutexcopies the lock state and breaks it.go vetwarns about this. Pass such structs by pointer. - Forgetting to initialise a map or slice field. A nil map inside a struct panics on write.
- Using positional struct literals.
Item{"Pen", 4000, 10}breaks when someone adds a field. Prefer named fields in real code.
Try it yourself
Create a BankAccount struct with an owner and a balance in paisa. Add Deposit and Withdraw methods with pointer receivers. Withdraw should return an error if the balance is too low. Write a String() method. Then change Deposit to a value receiver and observe that the balance never changes.
package main
import (
"fmt"
"strings"
)
type Item struct {
Name string
Price int // in paisa
Quantity int
}
// value receiver: works on a copy, good for read-only methods
func (i Item) Total() int {
return i.Price * i.Quantity
}
type Invoice struct {
Number string
Customer string
Items []Item
}
// constructor function by convention
func NewInvoice(number, customer string) *Invoice {
return &Invoice{Number: number, Customer: customer}
}
// pointer receiver: can change the invoice
func (inv *Invoice) Add(name string, price, qty int) {
inv.Items = append(inv.Items, Item{Name: name, Price: price, Quantity: qty})
}
func (inv Invoice) Total() int {
sum := 0
for _, it := range inv.Items {
sum += it.Total()
}
return sum
}
func (inv Invoice) String() string {
var sb strings.Builder
fmt.Fprintf(&sb, "Invoice %s for %s\n", inv.Number, inv.Customer)
for _, it := range inv.Items {
fmt.Fprintf(&sb, " %-12s %3d x %8.2f\n", it.Name, it.Quantity, float64(it.Price)/100)
}
fmt.Fprintf(&sb, " Total: Rs %.2f", float64(inv.Total())/100)
return sb.String()
}
func main() {
inv := NewInvoice("INV-001", "Ali Traders")
inv.Add("Paper ream", 125050, 4)
inv.Add("Stapler", 48000, 2)
fmt.Println(inv)
line := Item{"Pen", 4000, 10}
fmt.Printf("%+v total %d\n", line, line.Total())
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account