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) }
(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:
type MyInt int) — you can add methods.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
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
Story
Story
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.