LEFT | RIGHT |
(no file at all) | |
| 1 package main |
| 2 |
| 3 import ( |
| 4 "fmt" |
| 5 "reflect" |
| 6 ) |
| 7 |
| 8 func main() { |
| 9 var x float64 = 3.4 |
| 10 fmt.Println("type:", reflect.TypeOf(x)) |
| 11 // STOP OMIT |
| 12 // TODO(proppy): test output OMIT |
| 13 } |
| 14 |
| 15 // STOP main OMIT |
| 16 |
| 17 func f1() { |
| 18 // START f1 OMIT |
| 19 var x float64 = 3.4 |
| 20 v := reflect.ValueOf(x) |
| 21 fmt.Println("type:", v.Type()) |
| 22 fmt.Println("kind is float64:", v.Kind() == reflect.Float64) |
| 23 fmt.Println("value:", v.Float()) |
| 24 // STOP OMIT |
| 25 } |
| 26 |
| 27 func f2() { |
| 28 // START f2 OMIT |
| 29 var x uint8 = 'x' |
| 30 v := reflect.ValueOf(x) |
| 31 fmt.Println("type:", v.Type()) // uint8. |
| 32 fmt.Println("kind is uint8: ", v.Kind() == reflect.Uint8) // true. |
| 33 x = uint8(v.Uint()) // v.Uint retu
rns a uint64. |
| 34 // STOP OMIT |
| 35 } |
| 36 |
| 37 func f3() { |
| 38 // START f3 OMIT |
| 39 type MyInt int |
| 40 var x MyInt = 7 |
| 41 v := reflect.ValueOf(x) |
| 42 // START f3b OMIT |
| 43 y := v.Interface().(float64) // y will have type float64. |
| 44 fmt.Println(y) |
| 45 // START f3c OMIT |
| 46 fmt.Println(v.Interface()) |
| 47 // START f3d OMIT |
| 48 fmt.Printf("value is %7.1e\n", v.Interface()) |
| 49 // STOP OMIT |
| 50 } |
| 51 |
| 52 func f4() { |
| 53 // START f4 OMIT |
| 54 var x float64 = 3.4 |
| 55 v := reflect.ValueOf(x) |
| 56 v.SetFloat(7.1) // Error: will panic. |
| 57 // STOP OMIT |
| 58 } |
| 59 |
| 60 func f5() { |
| 61 // START f5 OMIT |
| 62 var x float64 = 3.4 |
| 63 v := reflect.ValueOf(x) |
| 64 fmt.Println("settability of v:", v.CanSet()) |
| 65 // STOP OMIT |
| 66 } |
| 67 |
| 68 func f6() { |
| 69 // START f6 OMIT |
| 70 var x float64 = 3.4 |
| 71 v := reflect.ValueOf(x) |
| 72 // START f6b OMIT |
| 73 v.SetFloat(7.1) |
| 74 // STOP OMIT |
| 75 } |
| 76 |
| 77 func f7() { |
| 78 // START f7 OMIT |
| 79 var x float64 = 3.4 |
| 80 p := reflect.ValueOf(&x) // Note: take the address of x. |
| 81 fmt.Println("type of p:", p.Type()) |
| 82 fmt.Println("settability of p:", p.CanSet()) |
| 83 // START f7b OMIT |
| 84 v := p.Elem() |
| 85 fmt.Println("settability of v:", v.CanSet()) |
| 86 // START f7c OMIT |
| 87 v.SetFloat(7.1) |
| 88 fmt.Println(v.Interface()) |
| 89 fmt.Println(x) |
| 90 // STOP OMIT |
| 91 } |
| 92 |
| 93 func f8() { |
| 94 // START f8 OMIT |
| 95 type T struct { |
| 96 A int |
| 97 B string |
| 98 } |
| 99 t := T{23, "skidoo"} |
| 100 s := reflect.ValueOf(&t).Elem() |
| 101 typeOfT := s.Type() |
| 102 for i := 0; i < s.NumField(); i++ { |
| 103 f := s.Field(i) |
| 104 fmt.Printf("%d: %s %s = %v\n", i, |
| 105 typeOfT.Field(i).Name, f.Type(), f.Interface()) |
| 106 } |
| 107 // START f8b OMIT |
| 108 s.Field(0).SetInt(77) |
| 109 s.Field(1).SetString("Sunset Strip") |
| 110 fmt.Println("t is now", t) |
| 111 // STOP OMIT |
| 112 } |
LEFT | RIGHT |