【Go】Implicitly implemented interface

Implicit implementation of the interface

Types implement interfaces by implementing all methods of an interface

1
2
3
4
5
6
7
8
9
10
11
12
13
// define the interface type MyInterface,
type MyInterface interface {
  f ()
}

type T struct {
  s string
}

// type T implements interface Myinterface
func (t T) M () {
  // do something
}

Type T implements the interface

Interface is also a value

Interface code implementation

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

import (
"fmt"
)

// define the interface type
type I interface {
M()
}

// define structure type T
type T struct {
S string
}

// type T implements interface I
func (t * T) M () {
fmt.Println(t.S)
}

// function, parameter is interface I
func describe (i I) {
fmt.Printf("(% v,% T) \n", i, i)
}

func main () {
  // declare a variable of type I interface i
var i I

i = &T{"Hello"}
describe(i)
i.M()
}

Save as helloworld.go, execution result

1
2
3
[me@VM_0_14_centos go] # go run helloworld.go
(& {Hello}, * main.T)
Helo

Inside Go, interface values ​​can be thought of as tuples containing values ​​and specific types: (value, type)

Here the variable i initialized on line 31 is the interface type

Its value is a pointer to {Hello}
Its type is a pointer to type T * main.T

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