Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 147 ยท Structs and Methods

Methods

Learn Go methods - how to declare them with receivers, put methods on any defined type, use method values and expressions, compare methods with functions, and understand method sets.

A method is a function with a special extra parameter called the receiver. The receiver ties the function to a type, so you can write rect.Area() instead of Area(rect). This is how Go attaches behavior to data. There are no classes: a struct declares the data, and methods declared anywhere in the same package add the behavior.

Methods make code read naturally, let types satisfy interfaces, and give each type its own namespace for operations. This lesson shows how to declare them, which types can have them, how to turn methods into function values, and how methods differ from plain functions. The choice between value and pointer receivers gets its own lesson next (Value vs Pointer Receivers); here we see enough of both to be productive. It assumes you know structs and pointers.

Declaring a method

A method declaration looks like a function declaration with the receiver in parentheses between func and the method name:

Go Your first methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

In func (c Circle) Area() float64, the receiver is c of type Circle. Inside the method it behaves like any parameter. By convention the receiver name is a short abbreviation of the type (one or two letters, such as c for Circle), the same in every method of that type, and never this or self.

Value receivers and pointer receivers

A receiver can be a value (c Circle) or a pointer (c *Circle):

  • With a value receiver, the method works on a copy. Changes inside the method do not affect the caller's value.
  • With a pointer receiver, the method works on the original and can modify it. It also avoids copying a large struct on each call.
Go Value receiver versus pointer receiver

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Look at c.Inc() in main. The variable c is a Counter, not a *Counter, yet the call works. When c is addressable (a variable, a field of an addressable struct, a slice element), Go rewrites c.Inc() to (&c).Inc() for you. The reverse also works: a pointer p can call a value method, and Go rewrites p.Value() to (*p).Value().

What does not work is calling a pointer method on a value that has no address, such as a composite literal or a map element:

Go Pointer method on a non-addressable value (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler says cannot call pointer method Inc on Counter, because the temporary Counter{} has no address to hand to Inc. Assign it to a variable first.

Methods on any defined type

You are not limited to structs. A method can be declared on any defined type in the same package: a struct, a slice, a map, a function type, or a number-based type. This is a big part of why Go's defined types are so useful.

Go Methods on non-struct types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

There is one restriction: the type must be declared in the same package as the method. You cannot add methods to int, string, or types from other packages directly:

Go Methods on built-in types (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The error is cannot define new methods on non-local type int. The cure is to define your own type (type MyInt int) and put the method on that.

Also note that a type with a pointer or interface as its underlying type cannot have methods, and that you cannot declare two methods with the same name on one type, nor a method and a field with the same name.

Method values and method expressions

A method can be used as a value in two ways.

A method value is x.Method without calling it. It produces a function that has the receiver already bound: calling it later uses that receiver. For a value receiver the receiver is copied at the moment you create the method value; for a pointer receiver the pointer is saved.

A method expression is Type.Method, which produces a plain function whose first parameter is the receiver.

Go Method values and method expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Method values are everywhere in real programs: passing server.handleIndex as an HTTP handler, defer mu.Unlock, or starting go worker.Run. They also work for sorting and callbacks:

Go Method values as callbacks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Methods versus functions

A method is just a function with the receiver as its first parameter: func (c Circle) Area() behaves like func Area(c Circle). So when should you write a method?

  • Use a method when the operation belongs to the type: it reads or updates the type's state, it should be part of an interface the type satisfies, or the name is naturally scoped to the type (buffer.Len(), t.Add(d)).
  • Use a function for operations over several unrelated types, for constructors (NewServer), for generic algorithms, and when the data is not "owned" by a single type.

Method names live inside the type's namespace, so Circle.Area and Square.Area can coexist without a prefix. Package-level functions all share one namespace.

Go has no method overloading. A type cannot have two methods with the same name but different parameters. This keeps method calls simple: the name alone identifies the method.

Method sets, briefly

The method set of a type is the collection of methods that are in scope when you use it as an interface value or through generics:

Type Method set contains
T methods with receiver T
*T methods with receiver T and *T

That is why this fails: an interface needs Inc, but Counter (the value) does not have it in its method set, since Inc has a pointer receiver.

Go A value does not have pointer methods in its method set (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The error is Counter does not implement Incer (method Inc has pointer receiver). Using &c as the value fixes it, because *Counter has both methods. The Value vs Pointer Receivers lesson explains how to choose and why mixing receiver kinds on one type is discouraged.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In func (r Rect) Area() float64, what is r?

    With a value receiver, r is a copy of the value the method is called on. A pointer receiver would be written (r *Rect).
  2. 2. What does this print? func (c Counter) Inc() { c.n++ } then var c Counter; c.Inc(); c.Inc(); fmt.Println(c.n)

    The value receiver gets a copy of c each time, so the original counter is never changed. Use a pointer receiver to modify it.
  3. 3. Which of these is NOT allowed?

    Methods can only be declared on types defined in the same package. int is not, so wrap it in your own defined type.
  4. 4. What is Greeter.Hello (without parentheses, where Hello has a value receiver)?

    Type.Method is a method expression. For a method with receiver Greeter and a parameter string, it has the type func(Greeter, string) string.
  5. 5. Which methods are in the method set of *T?

    The method set of *T includes the methods of T and those with receiver *T. The method set of T includes only value-receiver methods.

Summary

  • A method is a function with a receiver, declared as func (r Type) Name(args) result, and called as value.Name(args).
  • Use short receiver names that match across all methods of a type.
  • A value receiver works on a copy; a pointer receiver can modify the original. Go converts between x.M() and (&x).M() automatically when x is addressable.
  • Methods may be declared on any defined type in the same package, not only structs; not on built-in or foreign types.
  • x.Method is a method value (receiver bound); Type.Method is a method expression (receiver as first argument).
  • Go has no overloading; method sets decide which methods an interface sees: T has value-receiver methods, *T has all of them.

Next: Value vs Pointer Receivers