码迷,mamicode.com
首页 > 其他好文 > 详细

golang reflect

时间:2018-11-16 00:24:38      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:bubuko   检查   动态   变量   port   hello   type   详细信息   package   

在计算机中,反射表示程序能够检查自身结构的一种能力,尤其是类型。通过反射,可以获取对象类型的详细信息,并可动态操作对象。

实现 包手册地址: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)
}

技术分享图片

 

golang reflect

标签:bubuko   检查   动态   变量   port   hello   type   详细信息   package   

原文地址:https://www.cnblogs.com/LC161616/p/9966909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!