Methods and receivers
Attach behaviour to a struct with methods, choose between value and pointer receivers, and write the constructor and method set a limiter type needs.
Learning outcomes
- Write a method with a value receiver and with a pointer receiver.
- Say which receiver to choose and why a type should not mix them.
- Call methods on values and pointers and know when Go takes the address for you.
- Write a NewX constructor and a method set for a small type.
What you will learn
In the previous lesson, you learned how structs hold related data and how pointers let multiple parts of a program refer to the same value.
Now you need a way to attach behavior to those types.
For example, a token bucket should be able to report its remaining tokens, consume a token, and refill its capacity. You could write separate functions that accept a Bucket or *Bucket, but Go provides a feature that makes this relationship clearer: methods.
By the end of this lesson, you should be able to:
- Define methods on your own types.
- Understand receivers and the difference between value and pointer receivers.
- Decide which receiver type to use.
- Create constructors and a consistent set of methods for a type.
- Understand method values and method expressions.
- Recognize methods on named types that are not structs.
Methods and receivers
A method is a function associated with a particular type. The value that a method operates on is called its receiver.
In Go, a method looks almost exactly like a regular function. The difference is that a receiver appears between the func keyword and the method name.
Consider a simple counter:
package main
import "fmt"
type Counter struct {
Count int
}
func (c Counter) Value() int {
return c.Count
}
func main() {
counter := Counter{Count: 10}
fmt.Println(counter.Value())
}Value is a method on Counter. The declaration:
func (c Counter) Value() intmeans that Value receives a Counter value named c and returns an integer.
The variable c is the receiver. By convention, receiver names are short, usually one or two characters, and consistent across the methods of a type. For Counter, c is reasonable. For Bucket, b is natural.
You call a method using a dot:
counter.Value()This makes it clear that the behavior belongs to the counter.
A method is a function with a receiver argument
Conceptually, Go treats a method call as a function call where the receiver is supplied as the first argument.
This method:
func (c Counter) Value() int {
return c.Count
}can be understood as a function receiving a Counter value:
func Value(c Counter) int {
return c.Count
}The method syntax makes the relationship between the operation and its type explicit.


This is a useful mental model because it explains why methods have receiver types and why the choice between a value and pointer receiver matters.
Value receivers
A value receiver receives a copy of the value on which the method is called.
package main
import "fmt"
type Counter struct {
Count int
}
func (c Counter) Value() int {
return c.Count
}
func (c Counter) Increment() {
c.Count++
}
func main() {
counter := Counter{Count: 10}
counter.Increment()
fmt.Println(counter.Count)
}Output:
10The method increments its local copy. The original counter remains unchanged.
This behavior follows the normal Go assignment rule: assigning a struct value copies its fields. A value receiver behaves similarly because the method receives its own copy.
Value receivers are appropriate when:
- The type represents a small value.
- The method does not need to modify the original value.
- Copying the value is inexpensive and safe.
For example, a method that reads a counter's current value is a natural value receiver.
func (c Counter) Value() int {
return c.Count
}There is no reason to share the original counter just to read one field.
Pointer receivers
A pointer receiver receives a pointer to the original value rather than a copy of the entire value.
Use *Type in the receiver declaration.
package main
import "fmt"
type Counter struct {
Count int
}
func (c *Counter) Increment() {
c.Count++
}
func (c Counter) Value() int {
return c.Count
}
func main() {
counter := Counter{Count: 10}
counter.Increment()
fmt.Println(counter.Value())
}Output:
11The Increment method receives a pointer to the original counter. Its update is visible to the caller.
A pointer receiver is appropriate when:
- The method needs to modify the receiver.
- Copying the value would be expensive.
- The type contains state that must be accessed through a shared instance.
- The type contains a lock or another value that must not be copied.
The last point matters for backend code. Later, your rate limiter will contain synchronization state. Copying a value that contains a lock can introduce serious correctness problems. You will learn about locks in the concurrency lessons. For now, establish the rule: types that contain locks should use pointer receivers and should not be copied after initialization.
Go automatically takes the address when possible
Suppose a method has a pointer receiver:
func (c *Counter) Increment() {
c.Count++
}You might expect to call it like this:
counter := Counter{Count: 10}
(&counter).Increment()That is valid, but Go allows a shorter form:
counter := Counter{Count: 10}
counter.Increment()If the value is addressable, Go automatically takes its address when calling a pointer receiver method.
An addressable value is one for which Go can obtain a stable memory address, such as a local variable.
This convenience means you do not need to write &counter every time you call a pointer receiver method.
However, it does not mean that every expression can be used this way. A temporary value returned directly from a function is not necessarily addressable.
Choosing between value and pointer receivers
A useful decision rule is:
| Situation | Receiver |
|---|---|
| Method reads a small, immutable value | Value |
| Method modifies the receiver | Pointer |
| Type contains a lock | Pointer |
| Copying the value is expensive | Pointer |
| Type consistently uses pointer receivers | Prefer pointer receivers for its other methods |
Consistency matters. If some methods use value receivers and others use pointer receivers without a good reason, it becomes harder to understand how the type is intended to be used.
For a mutable backend type such as Bucket, use pointer receivers consistently.
type Bucket struct {
Tokens float64
}
func (b *Bucket) Consume() bool {
if b.Tokens < 1 {
return false
}
b.Tokens--
return true
}
func (b *Bucket) Remaining() float64 {
return b.Tokens
}Both methods use pointer receivers because they belong to a type whose state changes over time.
The Remaining method does not modify the bucket, but using a pointer receiver keeps the receiver convention consistent across the type.
Constructors and method sets
A constructor is a function that creates a value and establishes its initial state. Go does not have a special constructor syntax. A common naming convention is NewTypeName.
Let's build a small bucket with a constructor and methods.
package main
import "fmt"
type Bucket struct {
Tokens float64
Capacity float64
}
func NewBucket(capacity float64) *Bucket {
return &Bucket{
Tokens: capacity,
Capacity: capacity,
}
}
func (b *Bucket) Consume() bool {
if b.Tokens < 1 {
return false
}
b.Tokens--
return true
}
func (b *Bucket) Refill() {
b.Tokens = b.Capacity
}
func (b *Bucket) Remaining() float64 {
return b.Tokens
}
func main() {
bucket := NewBucket(5)
fmt.Println(bucket.Consume())
fmt.Println(bucket.Remaining())
bucket.Refill()
fmt.Println(bucket.Remaining())
}Output:
true
4
5The constructor returns *Bucket, so callers receive a pointer to the newly created bucket.
The methods define the operations that callers can perform on that bucket:
Consumeremoves one token when enough tokens remain.Refillrestores the bucket to its configured capacity.Remainingreports the current token count.
This is a small example of encapsulating behavior with data. The struct stores the state, and its methods define operations on that state.
The method set
A method set is the collection of methods associated with a type under Go's receiver rules.
For a type T:
- The method set of
Tincludes methods declared with receiverT. - The method set of
*Tincludes methods declared with receiverTand*T.
For example:
type Counter struct {
Count int
}
func (c Counter) Value() int {
return c.Count
}
func (c *Counter) Increment() {
c.Count++
}A Counter value has the Value method in its method set. A *Counter pointer has both Value and Increment.
This distinction becomes important when you learn interfaces in the next lesson. Whether a type satisfies an interface depends on its method set.
For now, remember that calling a pointer receiver method on an addressable value is convenient, but that convenience does not change the formal method set of the value type.
Method values and method expressions
Go allows you to treat methods as function values. This is useful when you want to store a method for later execution or pass it to another function.
Method values
A method value is a method assigned to a variable. The receiver is already associated with that method value.
package main
import "fmt"
type Counter struct {
Count int
}
func (c *Counter) Increment() {
c.Count++
}
func main() {
counter := Counter{Count: 10}
increment := counter.Increment
increment()
increment()
fmt.Println(counter.Count)
}Output:
12The variable increment holds a callable method value associated with counter.
You can invoke it like an ordinary function:
increment()You do not need to provide the receiver again because it was captured when the method value was created.
This is conceptually similar to storing a function value or closure, which you encountered in the previous lesson.
Method expressions
A method expression creates a function from a method without binding it to a particular receiver.
package main
import "fmt"
type Counter struct {
Count int
}
func (c *Counter) Increment() {
c.Count++
}
func main() {
increment := (*Counter).Increment
counter := Counter{Count: 10}
increment(&counter)
fmt.Println(counter.Count)
}Output:
11Notice the difference:
counter.Incrementis a method value. The receiver is already selected.(*Counter).Incrementis a method expression. The receiver must be supplied when calling the resulting function.
Method expressions are less common in everyday application code, but they help explain how methods relate to ordinary functions.
Methods on named types that are not structs
Methods are not limited to struct types. Go allows you to define methods on a named type whose underlying type is another built-in type.
For example, you can define a type for temperatures:
package main
import "fmt"
type Celsius float64
func (c Celsius) IsFreezing() bool {
return c <= 0
}
func main() {
temperature := Celsius(-5)
fmt.Println(temperature.IsFreezing())
}Output:
trueCelsius is a named type based on float64. It has its own identity and can have methods.
This is useful when a value has a specific meaning that should be represented explicitly. A duration, temperature, or percentage can be modeled as a named type rather than using an ordinary number everywhere.
There is one important restriction: you can define methods only on a type declared in the same package as the method. You cannot add methods directly to built-in types or types owned by another package.
Exported and unexported methods
Go uses capitalization to control visibility across package boundaries.
An exported method begins with an uppercase letter:
func (b *Bucket) Consume() bool {
return true
}An unexported method begins with a lowercase letter:
func (b *Bucket) refill() {
b.Tokens = b.Capacity
}Code in another package can call Consume, but it cannot call refill.
This convention helps define which operations are part of a package's public API and which are implementation details.
For the course project, types and methods that need to be used from other packages should be exported deliberately. For example, a limiter type in backend/internal/ratelimit may expose methods that the HTTP layer needs to call, while keeping internal helper methods unexported.
Zero values and useful defaults
A type's zero value is the value it receives when declared without an explicit initializer.
Structs can have useful zero values, and methods can be designed to work correctly with them.
package main
import "fmt"
type Counter struct {
Count int
}
func (c *Counter) Increment() {
c.Count++
}
func (c Counter) Value() int {
return c.Count
}
func main() {
var counter Counter
counter.Increment()
counter.Increment()
fmt.Println(counter.Value())
}Output:
2The zero value of Counter is immediately usable. There is no constructor requirement because the default count of zero is valid.
Not every type has a useful zero value. A Bucket, for example, may need a nonzero capacity supplied during construction. In that case, a constructor makes the required initialization explicit.
A good Go type is often designed so that its zero value is useful whenever that makes sense for the domain.
Common mistakes to avoid
- Using a value receiver for a method that is supposed to modify the original value. The method changes only its copy.
- Using pointer receivers inconsistently without a reason. Pick a clear convention for each type.
- Assuming Go's automatic address-taking changes the method set of a value type. It only makes certain method calls more convenient.
- Copying a type that contains a lock. This can break synchronization assumptions. Use pointer receivers and avoid copying such values.
- Giving receiver variables long or inconsistent names. Use short names that identify the receiver type.
- Making every method exported. Keep implementation details unexported unless other packages need them.
- Assuming every type needs a constructor. If the zero value is valid and useful, callers can often declare the type directly.
Knowledge assessment
What is a receiver in Go, and how does a method differ from an ordinary function?
Practical applications
- Practice exercise 1.8, Write your first Go program: Define a small type and attach behavior to it using methods.
- Exercise 1.11, Token bucket: Implement methods such as
Consume,Refill, andRemainingon the bucket type. Use pointer receivers because the bucket's state changes. - Exercise 1.14, Fixed window: Attach operations to the fixed-window limiter type and use a consistent receiver convention.
The key design decision is simple: choose receivers based on whether the method needs to share or modify the original value. That decision will become increasingly important as the rate limiter grows.
References
Everything above is explained on this page; these are where it comes from (Go 1.2x).