-
Notifications
You must be signed in to change notification settings - Fork 86
/
setable.go
54 lines (45 loc) · 931 Bytes
/
setable.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
package main
import (
"fmt"
"reflect"
)
func main() {
setable()
canSetExample()
canNotSetExample()
}
func setable() {
x := 10
v1 := reflect.ValueOf(x)
fmt.Println("setable:", v1.CanSet())
p := reflect.ValueOf(&x)
fmt.Println("setable:", p.CanSet())
v2 := p.Elem()
fmt.Println("setable:", v2.CanSet())
// 结果
// setable: false
// setable: false
// setable: true
}
// 增加recover
func canNotSetExample() {
x := 10
v := reflect.ValueOf(x)
changeToSeven(v)
fmt.Println("value outside:", v.Interface())
// 结果
// value outside: 7
}
// BUG, it shoule be failed and panic
func canSetExample() {
x := 10
v := reflect.ValueOf(&x).Elem()
changeToSeven(v)
fmt.Println("value outside:", v.Interface())
// 结果
// panic: reflect: reflect.Value.SetInt using unaddressable value
}
// Can not set, if you set a non-setability Value, it will panic
func changeToSeven(v reflect.Value) {
v.SetInt(7)
}