Methods on non struct-types
Methods are functions with a receiver parameter
The receiver doesn’t need to be a struct. We can declare methods on non-struct types too.
You can only declare a method with a receiver whose type is defined in the same package as the method. You cannot declare a method with receiver whose type is defined in another package (which includes built-in types such as int
)
1package main
2
3import (
4 "fmt"
5 "math"
6)
7
8type MyFloat float64
9
10func (f MyFloat) Abs() float64 {
11 if f < 0 {
12 return float64(-f)
13 }
14 return float64(f)
15}
16
17func main() {
18 f := MyFloat(-math.Sqrt2)
19 fmt.Println(f.Abs())
20}