Methods
In this page:
Defining a Method
A method looks like a regular function but has an extra receiver parameter before the method name, which associates it with a specific type -- calling it uses dot notation on a value of that type, like p.Greet().
Example: Defining a Method
package main
import "fmt"
type Person struct {
Name string
}
func (p Person) Greet() string {
return "Hello, " + p.Name
}
func main() {
p := Person{Name: "Rohan"}
fmt.Println(p.Greet())
}
Login to try C/C++/Java/PHP code in the editor
Methods vs Functions
A method is really just syntactic sugar for a function that takes the receiver as its first argument -- the difference is purely how it's called (dot notation) and that it can only be attached to types in the same package.
Example: Methods vs Functions
package main
import "fmt"
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func main() {
r := Rectangle{Width: 4, Height: 5}
fmt.Println("area:", r.Area())
}
Login to try C/C++/Java/PHP code in the editor
Methods on Non-Struct Types
Methods aren't limited to structs -- you can define a method on any named type declared in your package, including one based on a simple type like int or string.
Note: This pattern is common for adding domain-specific behavior to simple values, like validating a custom type.
Example: Methods on Non-Struct Types
package main
import "fmt"
type Celsius float64
func (c Celsius) ToFahrenheit() float64 {
return float64(c)*9/5 + 32
}
func main() {
temp := Celsius(25)
fmt.Println(temp.ToFahrenheit())
}
Login to try C/C++/Java/PHP code in the editor
- Defining a method with the receiver type in the wrong position, forgetting it goes between func and the method name.
- Trying to define a method on a type declared in a different package, which Go does not allow -- you can only add methods to types you own.
- Confusing a method (tied to a specific type via a receiver) with a plain standalone function.
- A method is a function with a special receiver argument, tying it to a specific type.
- The receiver appears in parentheses between func and the method name.
- Methods can only be defined on types declared in the same package.
- Methods are the building block Go uses for attaching behavior to data, in place of class methods.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: