1. 程式人生 > >golang reflect

golang reflect

在計算機中,反射表示程式能夠檢查自身結構的一種能力,尤其是型別。通過反射,可以獲取物件型別的詳細資訊,並可動態操作物件。

實現 包手冊地址:https://studygolang.com/static/pkgdoc/pkg/reflect.htm

Import ("reflect")

常用的主要有 type value kind

reflect.TypeOf 獲取變數的型別,返回reflect.Type型別

reflect.Value.Kind,獲取變數的類別,返回一個常量

package main

import (
	"fmt"
	"reflect"
)

type user struct {
	name string
	id   int
	age  uint8
}

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

func info(o interface{}) {
	t := reflect.TypeOf(o)
	fmt.Println(t.Kind()) //kind返回型別的常量
	fmt.Println(t)        //TypeOf返回的是型別 package.type
}

func main() {
	var stu = user{
		name: "zhangsan",
		id:   1,
		age:  22,
	}

	stu.hello()
	info(stu)

	info("string")
}

 

package main

import (
	"fmt"
	"reflect"
)

type user struct {
	name string
	id   int
	age  uint8
}

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

func info(o interface{}) {
	v := reflect.ValueOf(o)

	iv := v.Interface()

	if typ, ok := iv.(user); ok == false {
		fmt.Printf("斷言的type為%T,o的type為%T\n", typ, iv)
	} else {
		fmt.Println("斷言成功")
	}

}

func main() {
	var stu = user{
		name: "zhangsan",
		id:   1,
		age:  22,
	}

	info(15)
	info(stu)
}