天天看點

Go反射介紹1.reflect代碼示例

1.reflect代碼示例

package main

import (
	"fmt"
	"reflect"
)

func RefectNum(arg interface{}) {
	fmt.Println("type :", reflect.TypeOf(arg))
	fmt.Println("value :", reflect.ValueOf(arg))

}

type Person struct {
	ID   int64
	Name string
	Age  int64
}

func (this *Person) Call() {
	fmt.Println("user is called ")
	fmt.Printf("user is %v\n", this)

}

func DoFileAndMethod(input interface{}) {
	// 擷取input的type
	inputType := reflect.TypeOf(input)
	// fmt.Println("input type:", inputType.Name()) // Person
	// 擷取Input的value
	inputValue := reflect.ValueOf(input)
	// fmt.Println("input type:", inputValue) // {1 Allice 24}

	// 通過type擷取裡面的字段
	// 1.擷取interface的reflect.Type,通過type得到NumField,進行周遊
	// 2.得到每個filed,資料類型
	// 3.通過每個field的interface{}擷取到對應的value
	for i := 0; i < inputType.NumField(); i++ {
		field := inputType.Field(i)
		value := inputValue.Field(i).Interface()
		fmt.Printf("%s:%v = %v\n", field.Name, field.Type, value)
	}
}
func main() {

	// var num float64 = 1.2345
	// RefectNum(num)

	user := Person{1, "Allice", 24}
	DoFileAndMethod(user)

}

// 結果:
input type: Person
input type: {1 Allice 24}
ID:int64 = 1
Name:string = Allice
Age:int64 = 24
           

感覺興趣的小夥伴可以加好友一起交流!!

Go反射介紹1.reflect代碼示例

繼續閱讀