Interfaces in Go
An interface type is defined as a set of method signatures.
We say a type implements an interface if the type has all the methods defined in the interface. There is no explicit declaration of intent.
A value of interface type can hold any value that implements those methods.
E.g.
1package main
2
3import (
4 "fmt"
5 "math"
6)
7
8type Abser interface {
9 Abs() float64
10}
11
12type Vertex struc {
13 X, Y float64
14}
15
16type MyFloat float64
17
18func (v *Vertex) Abs() float64 {
19 return math.Sqrt(v.X*v.X + v.Y*v.Y)
20}
21
22func (mf MyFloat) Abs() float64 {
23 if mf < 0 {
24 return float64(-mf)
25 }
26
27 return float64(mf)
28}
29
30func main() {
31 var a Abser
32 f := MyFloat(-math.Sqrt2)
33 v := Vertex{3, 4}
34
35 a = f // a MyFloat implements Abser
36 a = &v // a *Vertex implements Abser
37
38 // In the following line, v is a Vertex (not *Vertex)
39 // and does NOT implement Abser
40 a = v
41
42 fmt.Println(a.Abs())
43}
References
Next -> interface-values-in-go
Next -> stringers-interface-in-go
Next -> errors-in-go
Next -> readers-in-go
#heap #for_the_love_of_go #programming #reference #pointer #value #pass_by #methods #interface #golang #stack