Menu
Coddy logo textTech

Defining Methods on Structs

Part of the Object Oriented Programming section of Coddy's GO journey — lesson 7 of 107.

Methods in Go are functions with a special receiver argument that associates the function with a struct type.

Method syntax

func (receiverName StructType) MethodName() ReturnType {
    // method body
}

Define a struct with methods

type Rectangle struct {
    Width  float64
    Height float64
}

func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

func (r Rectangle) Perimeter() float64 {
    return 2 * (r.Width + r.Height)
}

Methods with parameters

func (r Rectangle) Scale(factor float64) float64 {
    return r.Area() * factor
}

Calling methods

rect := Rectangle{Width: 5, Height: 3}
fmt.Println(rect.Area())      // Output: 15
fmt.Println(rect.Perimeter()) // Output: 16
fmt.Println(rect.Scale(2))    // Output: 30

The receiver (r Rectangle) lets you access the struct's fields inside the method using the receiver variable r. Methods can call other methods on the same struct.

challenge icon

Challenge

Medium

Add three methods to the Circle struct:

  • Area — returns math.Pi * radius * radius
  • Circumference — returns 2 * math.Pi * radius
  • Describe — returns a string: "Circle with radius X.XX"

Cheat sheet

Methods in Go are functions with a special receiver argument that associates the function with a struct type.

Method syntax:

func (receiverName StructType) MethodName() ReturnType {
    // method body
}

Example with a struct and methods:

type Rectangle struct {
    Width  float64
    Height float64
}

func (r Rectangle) Area() float64 {
    return r.Width * r.Height
}

func (r Rectangle) Perimeter() float64 {
    return 2 * (r.Width + r.Height)
}

Methods can accept parameters:

func (r Rectangle) Scale(factor float64) float64 {
    return r.Area() * factor
}

Calling methods:

rect := Rectangle{Width: 5, Height: 3}
fmt.Println(rect.Area())      // Output: 15
fmt.Println(rect.Perimeter()) // Output: 16
fmt.Println(rect.Scale(2))    // Output: 30

The receiver allows you to access the struct's fields inside the method. Methods can call other methods on the same struct.

Try it yourself

package main

import "fmt"

func main() {
    var radius float64
    fmt.Scan(&radius)

    c := Circle{Radius: radius}

    fmt.Printf("Area: %.2f\n", c.Area())
    fmt.Printf("Circumference: %.2f\n", c.Circumference())
    fmt.Printf("Description: %s\n", c.Describe())
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming