2. Type Value harry potter 33 int 33 Type Value string harry potter .
3. Type Value var s string s = harry potter var x int x = 33 int x Type Value string harry potter 33 . s
4. reection var x int x = 33 Type Value int x 33 reection x reect.TypeOf(x) reect.ValueOf(x) x Value reect.ValueOf(x).Int() x Value
5. interface{} var all_type interface{} var xi int var xs string var xf oat32 go lang all_type = xi fmt.Println(" int ", reect.TypeOf(all_type)) all_type = xs fmt.Println(" string ", reect.TypeOf(all_type)) all_type = xf fmt.Println(" oat32 ", reect.TypeOf(all_type))
6. : interface (1/3) type Stringer interface { String() string } string type Binary uint64 // Binary Stringer . func (i Binary) String() string { return strconv.Itoa(i.Get()) } //int func (i Binary) Get() int { return int(i) }
7. : interface (2/3) func ToString(any interface{}) string { switch vi := any.(type) { case uint64: return strconv.Itoa(int(vi)) case Binary: return strconv.Itoa(int(vi)) } return "error" } interface{} ToString
8. : interface (3/3) ffunc main() { b := Binary(200) s := Stringer(b) var c interface{} = b // b . fmt.Println("string ", s.String()) fmt.Println(" bbbb", b) fmt.Println("ccccc ", c) fmt.Println("bbbbb string ", b.String()) fmt.Println("To String ", ToString(c)) fmt.Println(" String ", s.String()) }
9. itable: b b s . . itable .
10. itable itable . . itable
11.
12. :
13.
14. (The Laws of Reection)
15. Rob Pike http://blog.golang/laws-of-reection reect.TypeOf(interface {}) Type, reect.ValueOf(interface{}) Value 1. . 2. . 3. . canSet( ) bool => true
16. 1. . var x oat64 = 3.4 v := reect.ValueOf(x) fmt.Println(type:, v.Type()) fmt.Println(kind is oat64:, v.Kind() == reect.Float64) fmt.Println(value:, v.Float()) // type: oat64 kind is oat64: true value: 3.4
17. (Type) (Kind) var x unit8 = x v := reect.ValueOf(x) fmt.Println(type:, v.Type()) // unit8. fmt.Print(kind is unit8: ,v.Kind() == reect.Unit8) // true. x = unit8(v.Unit()) // v.Unit returns a unit64. type MyInt int var x MyInt = 7 v := reect.ValueOf(x) fmt.Println(kind is Int: , v.Kind() == reect.Int) // true
18. 2. . // Interface interface{} v . // func (v value) Interface() interface{} y := v.Interface().(oat64) // y oat64 . fmt.Println(y) fmt.Printf(value is %7.1en, v.Interface()) // 3.4e+00 , ValueOf . interface{} . : .
19. 3. . var x oat64 = 3.4 v := reect.ValueOf(x) v.SetFloat(7.1) // : . // : reect.Value.SetFloat var x oat64 = 3.4 v := reect.ValueOf(x) fmt.Println(settability of v:, v.CanSet()) // settability of v: false settability ?
20. settability . var x oat64 = 3.4 // x . v := reect.ValueOf(x) // f(x) f(&x) . // v.SetFloat(7.1) . , ?
21. , Luke var x oat64 = 3.4 p := reect.ValueOf(&x) // x . fmt.Println("type of p:", p.Type()) // type of p: *oat64 fmt.Println("settability of p:", p.CanSet()) // settable of p: false v := p.Elem() fmt.Println(" vvvv ", v) fmt.Println("settable of v:", v.CanSet()) v.SetFloat(7.1) fmt.Println(v.Interface()) // 7.1 fmt.Println(x) //7.1