Lesson 12 of 20 · Part 4: Types and abstraction
Methods and embedding
Learn Go methods for beginners. Value and pointer receivers, methods on your own types, constructor functions, and reusing code with struct embedding.
4 min read · Updated · Beginner friendly
What you'll learn
- Attach methods to your own types
- Choose between value and pointer receivers
- Write constructor functions like NewAccount
- Reuse fields and methods with struct embedding
In lesson 8 you grouped data into structs, and in lesson 9 you wrote functions that work on data. A method brings the two together: it’s a function that belongs to a type. Instead of area(rect) you write rect.Area(), which reads more naturally and keeps behaviour next to the data it works on.
Declaring a method
A method is a function with a receiver, an extra parameter written in parentheses before the function name:
package main
import "fmt"
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func (r Rectangle) Perimeter() float64 {
return 2 * (r.Width + r.Height)
}
func main() {
r := Rectangle{Width: 3, Height: 4}
fmt.Println("area:", r.Area())
fmt.Println("perimeter:", r.Perimeter())
}area: 12
perimeter: 14(r Rectangle) is the receiver. Inside the method, r is the rectangle the method was called on. By convention, the receiver name is a short abbreviation of the type, like r for Rectangle, not this or self.
Pointer receivers: methods that change the value
A receiver works like any other parameter: it’s a copy. A method with a value receiver can’t change the original. To modify it, use a pointer receiver, *Type:
package main
import "fmt"
type Counter struct {
hits int
}
func (c Counter) IncrementCopy() {
c.hits++ // changes a copy, then the copy is thrown away
}
func (c *Counter) Increment() {
c.hits++ // changes the real counter
}
func (c Counter) Hits() int {
return c.hits
}
func main() {
var c Counter
c.IncrementCopy()
fmt.Println("after IncrementCopy:", c.Hits())
c.Increment()
c.Increment()
fmt.Println("after Increment x2:", c.Hits())
}after IncrementCopy: 0
after Increment x2: 2Notice that we called c.Increment() on a plain Counter variable, not a pointer. Go automatically takes the address for you ((&c).Increment()), so you don’t have to write & yourself.
Value or pointer receiver?
Use a pointer receiver if the method changes the receiver, if the struct is large, or if it contains something that must not be copied (like a mutex, lesson 17). Otherwise a value receiver is fine. If any method of a type needs a pointer receiver, it’s common to make all its methods use pointer receivers, for consistency.
Methods on any type you define
Methods aren’t only for structs. You can define a new type based on a basic type and give it methods:
package main
import "fmt"
type Celsius float64
func (c Celsius) Fahrenheit() float64 {
return float64(c)*9/5 + 32
}
func (c Celsius) IsFreezing() bool {
return c <= 0
}
func main() {
temps := []Celsius{-5, 0, 21.5, 37}
for _, t := range temps {
fmt.Printf("%5.1f°C = %5.1f°F freezing=%t\n", float64(t), t.Fahrenheit(), t.IsFreezing())
}
} -5.0°C = 23.0°F freezing=true
0.0°C = 32.0°F freezing=true
21.5°C = 70.7°F freezing=false
37.0°C = 98.6°F freezing=falseCelsius is a new type whose underlying type is float64. It behaves like a number, but because it’s a separate type, Go won’t let you mix it up with an unrelated float64 such as a distance by accident. float64(t) converts it back when you need a plain number.
You can only define methods on types declared in your own package. You can’t add a method to int or string directly, which is why we declared Celsius first.
Constructor functions
Go has no special constructor syntax. By convention, you write a regular function called NewTypeName that creates a value, fills in defaults and validates the input:
package main
import (
"errors"
"fmt"
)
type Account struct {
owner string
balance float64
}
func NewAccount(owner string) (*Account, error) {
if owner == "" {
return nil, errors.New("owner is required")
}
return &Account{owner: owner}, nil
}
func (a *Account) Deposit(amount float64) {
a.balance += amount
}
func (a *Account) Withdraw(amount float64) error {
if amount > a.balance {
return fmt.Errorf("cannot withdraw %.2f: balance is %.2f", amount, a.balance)
}
a.balance -= amount
return nil
}
func (a *Account) Balance() float64 {
return a.balance
}
func main() {
acc, err := NewAccount("Ada")
if err != nil {
fmt.Println(err)
return
}
acc.Deposit(100)
if err := acc.Withdraw(250); err != nil {
fmt.Println("error:", err)
}
_ = acc.Withdraw(40)
fmt.Println("balance:", acc.Balance())
}error: cannot withdraw 250.00: balance is 100.00
balance: 60The fields owner and balance are lowercase, so code in other packages can’t change them directly; they must go through Deposit and Withdraw. This is how Go does encapsulation: with package-level visibility rather than private keywords.
Embedding: reuse without inheritance
Go has no inheritance. Instead, you can embed one type inside another by listing it as a field with no name. The fields and methods of the embedded type are promoted: you can use them as if they belonged to the outer type.
package main
import "fmt"
type Person struct {
Name string
Email string
}
func (p Person) Contact() string {
return p.Name + " <" + p.Email + ">"
}
type Employee struct {
Person // embedded: no field name
Title string
}
func main() {
e := Employee{
Person: Person{Name: "Grace", Email: "grace@example.com"},
Title: "Engineer",
}
fmt.Println(e.Name) // promoted field
fmt.Println(e.Contact()) // promoted method
fmt.Println(e.Title)
fmt.Println(e.Person.Name) // the embedded value is still reachable by its type name
}Grace
Grace <grace@example.com>
Engineer
GraceAn Employee has a Person; it isn’t a subclass of one. This is composition. You build bigger types out of smaller ones instead of building class hierarchies.
Overriding a promoted method
If the outer type defines a method with the same name, it takes priority. The embedded method is still available through the field:
package main
import "fmt"
type Logger struct{ prefix string }
func (l Logger) Log(msg string) {
fmt.Println(l.prefix + msg)
}
type Service struct {
Logger
name string
}
func (s Service) Log(msg string) {
s.Logger.Log("[" + s.name + "] " + msg) // call the embedded version
}
func main() {
s := Service{Logger: Logger{prefix: "LOG "}, name: "payments"}
s.Log("started")
}LOG [payments] startedExercises
1. Circle methods. Define type Circle struct { Radius float64 } with methods Area() and Scale(factor float64). Scale should change the circle’s radius, so think about which receiver it needs. Print the area before and after scaling by 2.
Show solution
package main
import (
"fmt"
"math"
)
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
func (c *Circle) Scale(factor float64) {
c.Radius *= factor
}
func main() {
c := Circle{Radius: 1}
fmt.Printf("before: %.2f\n", c.Area())
c.Scale(2)
fmt.Printf("after: %.2f\n", c.Area())
}before: 3.14
after: 12.57Scale changes the circle, so it needs a pointer receiver. Doubling the radius makes the area four times bigger.
2. A Stack type. Create type Stack struct { items []int } with methods Push(n int), Pop() (int, bool) (returns false when empty) and Len() int. Push 1, 2, 3, then pop everything.
Show solution
package main
import "fmt"
type Stack struct {
items []int
}
func (s *Stack) Push(n int) {
s.items = append(s.items, n)
}
func (s *Stack) Pop() (int, bool) {
if len(s.items) == 0 {
return 0, false
}
last := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return last, true
}
func (s *Stack) Len() int {
return len(s.items)
}
func main() {
var s Stack
for i := 1; i <= 3; i++ {
s.Push(i)
}
fmt.Println("size:", s.Len())
for {
n, ok := s.Pop()
if !ok {
break
}
fmt.Println("popped", n)
}
}size: 3
popped 3
popped 2
popped 1Push and Pop change the stack, so they need pointer receivers. In lesson 14 you’ll make this stack work for any type with generics.
3. Embedding. Create a Timestamps struct with CreatedBy string and a method Audit() string returning "created by " + CreatedBy. Embed it in a Post struct with a Title, and call Audit() on a post.
Show solution
package main
import "fmt"
type Timestamps struct {
CreatedBy string
}
func (t Timestamps) Audit() string {
return "created by " + t.CreatedBy
}
type Post struct {
Timestamps
Title string
}
func main() {
p := Post{Timestamps: Timestamps{CreatedBy: "Ada"}, Title: "Hello Go"}
fmt.Println(p.Title, "-", p.Audit())
}Hello Go - created by AdaRecap
- A method is a function with a receiver:
func (r Rect) Area() float64. - Value receivers get a copy; pointer receivers (
*T) can change the original. - Any type declared in your package can have methods, not just structs.
NewXfunctions act as constructors; lowercase fields hide data from other packages.- Embedding promotes fields and methods: composition instead of inheritance.
Next you’ll meet Go’s most powerful idea for flexible code: interfaces.
Finished this lesson?
Your progress is saved in this browser only.