← Back to Go Course | Chapter 6: Structs & Methods | Lesson 3 of 6

Methods

A method is a function that's attached to a specific type, like giving every Car its own built-in Honk action it can perform.

Defining a Method

A method looks like a regular function but has an extra receiver parameter before the method name, which associates it with a specific type -- calling it uses dot notation on a value of that type, like p.Greet().

Example: Defining a Method

markup
package main

import "fmt"

type Person struct {
	Name string
}

func (p Person) Greet() string {
	return "Hello, " + p.Name
}

func main() {
	p := Person{Name: "Rohan"}
	fmt.Println(p.Greet())
}

Methods vs Functions

A method is really just syntactic sugar for a function that takes the receiver as its first argument -- the difference is purely how it's called (dot notation) and that it can only be attached to types in the same package.

Example: Methods vs Functions

markup
package main

import "fmt"

type Rectangle struct {
	Width, Height float64
}

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

func main() {
	r := Rectangle{Width: 4, Height: 5}
	fmt.Println("area:", r.Area())
}

Methods on Non-Struct Types

Methods aren't limited to structs -- you can define a method on any named type declared in your package, including one based on a simple type like int or string.

Note: This pattern is common for adding domain-specific behavior to simple values, like validating a custom type.

Example: Methods on Non-Struct Types

markup
package main

import "fmt"

type Celsius float64

func (c Celsius) ToFahrenheit() float64 {
	return float64(c)*9/5 + 32
}

func main() {
	temp := Celsius(25)
	fmt.Println(temp.ToFahrenheit())
}
Common Mistakes
  1. Defining a method with the receiver type in the wrong position, forgetting it goes between func and the method name.
  2. Trying to define a method on a type declared in a different package, which Go does not allow -- you can only add methods to types you own.
  3. Confusing a method (tied to a specific type via a receiver) with a plain standalone function.
Chapter Summary
  • A method is a function with a special receiver argument, tying it to a specific type.
  • The receiver appears in parentheses between func and the method name.
  • Methods can only be defined on types declared in the same package.
  • Methods are the building block Go uses for attaching behavior to data, in place of class methods.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.