go學習-反射

定義

package main

import (
	"fmt"
	"reflect"
)

type user struct {
	Id   int
	Name string
	Age  int
}

func (u user) Hello() {
	fmt.Println("hello world")
}

func main() {
	u := user{1, "cll", 12}
	info(u)
}

func info(o interface{}) {
	t := reflect.TypeOf(o)
	fmt.Println("type:" + t.Name())

	v := reflect.ValueOf(o)
	fmt.Println("fields:")

	for i := 0; i < t.NumField(); i++ {
		f := t.Field(i)
		val := v.Field(i).Interface()
		fmt.Printf("%6s:%v = %v\n", f.Name, f.Type, val)
	}

	for i := 0; i < t.NumMethod(); i++ {
		m := t.Method(i)
		fmt.Printf("%6s:%v\n", m.Name, m.Type)
	}
}

參考:

https://studygolang.com/articles/2762


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章