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
| package main
import ( "fmt" "reflect" )
func main() {
// 反射对基本类型操作 //var num int = 10 //testReflect01(num)
// 反射对结构体操作 //var stu = Student{ // Name: "fuyi", // Age: 22, //} //testReflect02(stu)
var num int = 10 testReflect03(&num) fmt.Printf("num: %v\n", num) }
func testReflect01(i interface{}) { rType := reflect.TypeOf(i) fmt.Printf("rType : %v, %T\n", rType, rType)
rVal := reflect.ValueOf(i) fmt.Printf("rVal : %v, %T\n", rVal, rVal)
// rVal转interface iV := rVal.Interface()
// 通过断言转具体类型 n := iV.(int) fmt.Println("n : ", n + 1) }
type Student struct { Name string Age int }
func testReflect02(i interface{}) { rType := reflect.TypeOf(i) fmt.Printf("rType : %v, %T\n", rType, rType)
rVal := reflect.ValueOf(i) fmt.Printf("rVal : %v, %T\n", rVal, rVal)
fmt.Printf("kind: rType=%v, rVal=%v\n", rType.Kind(), rVal.Kind())
iV := rVal.Interface() stu, ok := iV.(Student) if ok { fmt.Printf("stu: %v, %v, %v", stu, stu.Name, stu.Age) } }
func testReflect03(i interface{}) { rVal := reflect.ValueOf(i) rVal.Elem().SetInt(20) }
|