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)
}

猜你喜欢

转载自www.cnblogs.com/LC161616/p/9966909.html