forked from guyan0319/golang_development_notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test1.go
55 lines (51 loc) · 1.17 KB
/
test1.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
package main
import (
"fmt"
"reflect"
)
type User struct {
Id int
Name string
Amount float64
}
type HandlerTypeVoid func()
type HandlerTypeString func() string
type HandlerTypeError func(interface{}) error
func main() {
var i interface{}
i = "string"
fmt.Println(i)
i = 1
fmt.Println(i)
i = User{Id: 2}
//i.(User).Id = 15 //运行此处会报错,在函数中修改interface表示的结构体的成员变量的值,编译时遇到这个编译错误,cannot assign to i.(User).Id
fmt.Println(i.(User).Id)
i = test
r := i.(func(v interface{}) error)("test_1")
fmt.Println(r)
//不同过反射调用函数
var err error
switch i.(type) { //通过使用.(type)方法可以利用switch来判断接口存储的类型。
case func(string):
case func(string, string):
//...
case func(interface{}) error:
if f, ok := i.(func(v interface{}) error); ok {
err = HandlerTypeError(f)("test_2")
}
break
default:
break
}
fmt.Println(err)
//通过反射
v := reflect.ValueOf(i)
rargs := make([]reflect.Value, 1)
rargs[0] = reflect.ValueOf("test_3")
res := v.Call(rargs)
fmt.Println(res)
}
func test(name interface{}) error {
fmt.Println(name)
return nil
}