【Go】Interface

Interface type is a collection defined by a set of method signatures

Interface type variables can hold any value that implements these methods, such as

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
package main

import (
  "fmt"
  "math"
)

type Abser interface {
  Abs ()float64
}

type MyFloat float64

func (f MyFloat) Abs() float64 {
  return float64(f)
}

type Vertex struct {
  X, Y float64
}

func (v * Vertex) Abs() float64 {
  return math.Sqrt(v.X)
}

func main() {
  var a Abser
  f: = MyFloat(math.Sqrt2)
  v: = Vertex {3, 4}

  a = f
  a = &v

  a = v

  fmt.Println(a.Abs())
}

Save helloworld.go, and execute the result:

1
2
3
4
[me@VM_0_14_centos go] # go run helloworld.go
# command-line-arguments
./helloworld.go:34:5: cannot use v (type Vertex) as type Abser in assignment:
Vertex does not implement Abser (Abs method has pointer receiver)

Above we defined an interface type Abser
Line 31 a = f, f is a MyFloat type, and a MyFloat type Abs implementation is implemented by line 14, so it is legal
Line 32 a = &v, &v is a Vertex type, and a 22 ​​Vertex type Abs implementation is implemented in line 22, so it is also legal

But line 34 a = v, v is a Vertex type, because the Abs implementation of the Vertex type is not implemented, the compilation fails

Persist in original technology sharing, your support will encourage me to continue to create!