Menu
Coddy logo textTech

Methods vs Functions

Part of the Logic & Flow section of Coddy's GO journey — lesson 10 of 68.

While both methods and functions perform operations in Go, they serve different purposes and have distinct declaration patterns. Understanding this difference is crucial for writing clear, organized code.

A function is standalone and independent. It doesn't belong to any specific type:

func calculateArea(width, height float64) float64 {
    return width * height
}

A method is attached to a specific type through a receiver. It belongs to that type and can access its data:

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

The key difference lies in how you call them. Functions are called directly by name, while methods are called on instances of their associated type using dot notation. This association makes methods perfect for defining behaviors that naturally belong to your custom types, while functions work well for general-purpose operations that don't need to be tied to specific data structures.

quiz iconTest yourself

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

quiz iconTest yourself

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

quiz iconTest yourself

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

Cheat sheet

A function is standalone and independent:

func calculateArea(width, height float64) float64 {
    return width * height
}

A method is attached to a specific type through a receiver:

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

Functions are called directly by name, while methods are called on instances using dot notation.

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

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

All lessons in Logic & Flow