Source file
tour/methods/interfaces.go
1
2
3 package main
4
5 import (
6 "fmt"
7 "math"
8 )
9
10 type Abser interface {
11 Abs() float64
12 }
13
14 func main() {
15 var a Abser
16 f := MyFloat(-math.Sqrt2)
17 v := Vertex{3, 4}
18
19 a = f
20 a = &v
21
22
23
24 a = v
25
26 fmt.Println(a.Abs())
27 }
28
29 type MyFloat float64
30
31 func (f MyFloat) Abs() float64 {
32 if f < 0 {
33 return float64(-f)
34 }
35 return float64(f)
36 }
37
38 type Vertex struct {
39 X, Y float64
40 }
41
42 func (v *Vertex) Abs() float64 {
43 return math.Sqrt(v.X*v.X + v.Y*v.Y)
44 }
45
View as plain text