↓ Skip to main content

Structs, Methods and Interfaces in Go

1094 words·6 mins· loading · loading ·
Table of Contents
Learn Golang - This article is part of a series.
Part 14: This Article

Updated 16 Nov 2026: rewritten. This version corrects the method-set rules, adds embedding, and ends with the two interfaces you’ll meet in almost every Go program, error and Stringer.

Go has no classes. It organises code around three smaller ideas: structs group data, methods attach behaviour to a type, and interfaces describe behaviour without saying who provides it. Together they cover what classes, inheritance and polymorphism do in other languages.

Structs
#

A struct is a collection of named fields:

Go
type Person struct {
	Name string
	Age  int
}

You can create one in several ways:

Go
a := Person{Name: "Ada", Age: 36} // named fields (preferred)
b := Person{"Alan", 41}           // positional: every field, in order
var c Person                      // zero value: Name is "", Age is 0
d := &Person{Name: "Grace"}       // a pointer to a new struct

Name the fields in a literal. The positional form breaks the moment someone adds a field to the struct.

Fields are read and written with a dot:

Go
a.Age = 37
fmt.Println(a.Name, a.Age) // Ada 37

Through a pointer you use the same dot, and Go dereferences for you: d.Name. A field whose name starts with a capital letter is exported, so other packages can use it. That’s also what the encoding/json package requires before it will read or write a field.

For a one-off value you don’t need a named type. An anonymous struct is declared in place:

Go
point := struct{ X, Y int }{1, 2}
fmt.Println(point.X, point.Y) // 1 2

Copying and comparing
#

Structs are values. Assigning or passing one copies all its fields, so changes to the copy don’t reach the original. To modify a struct in a function, pass a pointer:

Go
func birthday(p *Person) {
	p.Age++
}

birthday(&a)

Two structs of the same type are equal if all their fields are equal, and you compare them with ==, as long as every field is itself comparable. A struct containing a slice or a map can’t be compared that way.

Methods
#

A method is a function with a receiver, a special first parameter written before the name:

Go
func (p Person) Greeting() string {
	return "Hi, I'm " + p.Name
}

fmt.Println(a.Greeting()) // Hi, I'm Ada

You can define methods on any type you declare in your package, not only structs.

Value or pointer receiver?
#

A receiver can be a value (p Person) or a pointer (p *Person).

Go
func (p *Person) HaveBirthday() {
	p.Age++
}

a.HaveBirthday()
  • A value receiver gets a copy, so the method can’t change the original.
  • A pointer receiver gets the address, so it can change the original and doesn’t copy a large struct on each call.

Use a pointer receiver when the method modifies the receiver or the struct is large. If any method on a type needs a pointer receiver, make them all pointer receivers so the type behaves consistently.

You can call a pointer-receiver method on an ordinary variable, as a.HaveBirthday() does. Go takes the variable’s address for you, as long as the variable is addressable. Where the distinction really matters is interfaces.

Method sets
#

The method set of a type is the list of methods that count when you ask whether it implements an interface:

  • The method set of T contains the methods with a value receiver.
  • The method set of *T contains the methods with a value receiver and a pointer receiver.

So if HaveBirthday has a pointer receiver, a plain Person value doesn’t satisfy an interface that requires it, but a *Person does.

Interfaces
#

An interface is a set of method signatures. Any type that has those methods satisfies the interface automatically. There’s no implements keyword:

Go
package main

import (
	"fmt"
	"math"
)

type Shape interface {
	Area() float64
}

type Circle struct {
	R float64
}

func (c Circle) Area() float64 {
	return math.Pi * c.R * c.R
}

type Rectangle struct {
	Width, Height float64
}

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

func main() {
	shapes := []Shape{
		Circle{R: 5},
		Rectangle{Width: 10, Height: 5},
	}

	for _, s := range shapes {
		fmt.Printf("area: %.2f\n", s.Area())
	}
}
area: 78.54
area: 50.00

Circle and Rectangle never mention Shape. They satisfy it because both have an Area() float64 method. The slice holds both types, and each call runs the right method. This is how Go does polymorphism.

Because satisfaction is implicit, the consumer defines the interface. A function that only needs to read data can accept io.Reader, and any type with a Read method works, including files, network connections and in-memory buffers. Keep interfaces small: one or two methods is typical.

The empty interface and type assertions
#

An interface with no methods is satisfied by every type. It’s written any (formerly interface{}). To get the concrete value back, use a type assertion:

Go
var v any = "hello"

s, ok := v.(string)
fmt.Println(s, ok) // hello true

n, ok := v.(int)
fmt.Println(n, ok) // 0 false

Use the two-value form. The one-value form panics if the type is wrong. Because any gives up compile-time checking, reach for it sparingly.

Two interfaces you’ll use everywhere
#

Go
type error interface {
	Error() string
}

type Stringer interface { // in package fmt
	String() string
}

Any type with an Error() string method is an error, which is how Go’s error handling works. Any type with a String() string method controls how fmt prints it:

Go
func (p Person) String() string {
	return p.Name + " (" + strconv.Itoa(p.Age) + ")"
}

fmt.Println(Person{Name: "Ada", Age: 36}) // Ada (36)

Embedding instead of inheritance
#

Go reuses code by embedding one struct in another. The outer type gains the inner type’s fields and methods:

Go
type Animal struct {
	Name string
}

func (a Animal) Speak() string {
	return a.Name + " makes a sound"
}

type Dog struct {
	Animal // embedded
	Breed  string
}

d := Dog{Animal: Animal{Name: "Rex"}, Breed: "Beagle"}
fmt.Println(d.Name)    // Rex: promoted from Animal
fmt.Println(d.Speak()) // Rex makes a sound

A Dog isn’t a subclass of Animal, and you can’t use one where the other is expected. It has an Animal inside it. This “composition over inheritance” is a deliberate design choice, and it avoids the deep class hierarchies that are hard to change later.

Putting it together
#

Structs hold your data, methods give it behaviour, and interfaces let other code depend on that behaviour instead of a concrete type. You now have the whole language foundation. The next two posts use it to build real programs: a web server and a DNS record checker.

Learn Golang - This article is part of a series.
Part 14: This Article

Related