TheRiver | blog

You have reached the world's edge, none but devils play past here

0%

golang 接口

前言

简单整理go的接口相关知识

接口的定义

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"
)

type data interface {
print()
}

type i int

func (i) print() {
fmt.Println("int")
}

type f float32

func (f) print() {
fmt.Println("float")
}

func main() {
var d data

var in i
d = in
d.print()

var flo f
d = flo
d.print()

}

一个类型实现了接口的所有方法,则这个类型就是实现了接口的类型,可以赋值给接口类型的值。具有面向对象的特征。

空接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main

import (
"fmt"
)

type nul interface {

}

func main() {
var i int = 10
var f float32 = 10.10
var s string = "10"

var data nul
data = i
fmt.Println(data)
data = f
fmt.Println(data)
data = s
fmt.Println(data)
}

空接口可以接受任意类型的值

flag.value

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//main.go
package main

import (
"flag"
"fmt"
)

var num = change("number", 0, "input a number, output num*2")

func main() {
flag.Parse()
fmt.Println(num)
}
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
//num.go
package main

import (
"flag"
"fmt"
"strconv"
)

type data struct {
number int64
}

func (d *data) String() string {
return fmt.Sprintf("output is %d", d.number)
}

func (d *data) Set(s string) error {
out, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return fmt.Errorf("error!")
}
d.number = out * 2
return nil
}

func change(name string, value int64, usage string) *data {
f := data{value}
flag.CommandLine.Var(&f, name, usage)
return &f
}

1
2
3
4
[*** ]$ ./main -number 100
output is 200
[*** ]$ ./main -number 1000
output is 2000

nil接口

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

import "fmt"

type test1 interface {
print()
}

type test2 struct {
i int
}

func (test2) print() {

}

func check(in test1) {
if in == nil {
fmt.Println("nil")
return
}
fmt.Println("not nil")
}
func main() {
var a test1
check(a)

var b test2
check(b)

}

nil
not nil 

一个包含nil指针/值的接口不是nil接口,test2实现了print函数,是test1的一个实现类型。但b不是nil

1
2
3
4
5
|-----------------|
| test2 |
|_________________| //type
| nil |
|-----------------| //value

todo

ending

----------- ending -----------