-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinterfaces.go
More file actions
52 lines (43 loc) · 1.04 KB
/
interfaces.go
File metadata and controls
52 lines (43 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// 15. Interfaces
package main
import (
"fmt"
"math"
)
// Interface type is define by set of methods
type Abser interface {
Abs() float64 // in this case one method :)
}
func main() {
var a Abser
f := MyFloat(-math.Sqrt2)
// Value of interface type can hold any value that
// implements those methods.
// In this case f is of type MyFloat, and we have Abs function
// in this type
a = f
v := Vertex{3, 4} // this is not a pointer
// so if we would assign:
// a = v will produce error
// instead we must a to a referece of a v
a = &v // because Abster is define only on *Vertex
fmt.Println(a.Abs())
}
// so we define some named type
type MyFloat float64
// and define method of that type
// or in other words this method's receiver is type MyFloat
func (f MyFloat) Abs() float64 {
if f < 0 {
return float64(-f)
}
return float64(f)
}
// let us define struct type
type Vertex struct {
X,Y float64
}
// and then func of that type, but that has pointer as receiver
func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}