Methods continued

You can declare a method on non-struct types, too.

In this example we see a numeric type MyFloat with an Abs method.

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 a receiver whose type is defined in another package (which includes the built-in types such as int).

methods-continued.go

  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. type MyFloat float64
  7. func (f MyFloat) Abs() float64 {
  8. if f < 0 {
  9. return float64(-f)
  10. }
  11. return float64(f)
  12. }
  13. func main() {
  14. f := MyFloat(-math.Sqrt2)
  15. fmt.Println(f.Abs())
  16. }