ProgrammingGo Developer

How do methods work for structs in Go? What is the difference between a method declaration and a function, and how are methods implemented for types based on aliases (type alias)?

Pass interviews with Hintsage AI assistant

Answer

In Go, methods are functions with a receiver indicating to which type the method belongs:

type User struct { Name string } func (u *User) SayHello() { fmt.Println("Hi,", u.Name) }
  • A method is associated with a specific type (e.g., User), while a function is not.
  • The receiver of the method ((u *User)) works like the first argument in a function, but the syntax and calls differ.

Important! Methods can only be declared for types defined in your package (no methods on types defined in other packages, including built-in types). Behavior with aliases (type alias) is special:

  • For new types based on existing ones (type MyInt int) — you can add methods.
  • For type aliases (type MyInt = int) — you cannot add methods, because it is just an alias.

Example:

type MyInt int func (m MyInt) Double() int { return int(m) * 2 } // Type alias type MyIntAlias = int // func (m MyIntAlias) Double() int { ... } // compilation error

Trick Question

Can you declare a method for a slice of type []int or for a type alias?

Answer: For a slice of a built-in type ([]int), you cannot declare methods. For a new custom type based on a slice — you can:

type MySlice []int func (s MySlice) Sum() int { ... } // allowed

For type aliases, you cannot:

type SuperSlice = []int // func (s SuperSlice) Sum() int { ... } // error

Examples of real errors due to a lack of knowledge of the topic nuances


Story

In a microservices project, a team defined a type alias for int64 (for identifiers) and tried to declare validation methods directly for it — the code would not compile, and they had to refactor all structures to support methods.

Story

In a backend project, they wrote methods for a custom slice but accidentally did not define a new type (type ... []T), and worked with the built-in []T, which is why they could not add any methods to work with the slice elements.

Story

When trying to add methods to types from an external package (e.g., time.Time) for standardizing date handling, it turned out that this is impossible in Go — they had to use composition and utility functions.