forked from unknwon/the-way-to-go_ZH_CN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple_interface3.go
executable file
·75 lines (62 loc) · 936 Bytes
/
simple_interface3.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// simple_interface2.go
package main
import (
"fmt"
)
type Simpler interface {
Get() int
Set(int)
}
type Simple struct {
i int
}
func (p *Simple) Get() int {
return p.i
}
func (p *Simple) Set(u int) {
p.i = u
}
type RSimple struct {
i int
j int
}
func (p *RSimple) Get() int {
return p.j
}
func (p *RSimple) Set(u int) {
p.j = u
}
func fI(it Simpler) int {
switch it.(type) {
case *Simple:
it.Set(5)
return it.Get()
case *RSimple:
it.Set(50)
return it.Get()
default:
return 99
}
return 0
}
func gI(any interface{}) int {
// return any.(Simpler).Get() // unsafe, runtime panic possible
if v, ok := any.(Simpler); ok {
return v.Get()
}
return 0 // default value
}
/* Output:
6
60
*/
func main() {
var s Simple = Simple{6}
fmt.Println(gI(&s)) // &s is required because Get() is defined with a receiver type pointer
var r RSimple = RSimple{60, 60}
fmt.Println(gI(&r))
}
/* Output:
6
60
*/