ProgramGuru

Methods in Go

Start with Methods in Go

A method is a function with a receiver parameter, associating behavior with a named Go type.

What you’ll learn

  • Explain the main purpose of methods in go.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Write func (r Rectangle) Area() int to declare a method. The receiver r identifies the value on which the method operates. Call it with rectangle.Area().

Methods can be defined on named types declared in the same package; the receiver need not be a struct, and it may be a value or pointer type where allowed. Choosing the receiver matters for copying and mutation.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for methodsMethod calls connect a receiver value to behavior.Rectangle instanceStep 1Call Area()Step 2Receiver rStep 3Compute Width×HeightStep 4Method calls connect a receiver value to behavior.
Method calls connect a receiver value to behavior.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

type Rectangle struct{ Width, Height int }

func (r Rectangle) Area() int { return r.Width * r.Height }
func main() {
	rectangle := Rectangle{Width: 6, Height: 4}
	fmt.Println("Area:", rectangle.Area())
}

Output

Area: 24

Trace what the program does

The call rectangle.Area() supplies rectangle as the receiver value. The method multiplies 6 by 4 and returns 24.

Avoid common mistakes

  • A method uses a receiver parameter before the method name; an ordinary function does not.
  • You generally cannot define methods on types declared in another package.

Try it yourself

Add a Perimeter method returning twice the sum of Width and Height.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

Which syntax declares a method on Rectangle?
Choose one answer. You can try again.

Answer and explanation

func (r Rectangle) Area() int

Correct. The call rectangle.

What you should remember

You have practiced Methods in Go in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Value Receivers →