golang 如何通过反射创建新对象
- 作者: 我心自知_
- 来源: 51数据库
- 2021-06-26
废话少说,直接贴代码~
type a struct {
name string
}
// 测试unit
func testreflect(t *testing.t) {
reflectnew((*a)(nil))
}
//反射创建新对象。
func reflectnew(target interface{}) {
if target == nil {
fmt.println("参数不能未空")
return
}
t := reflect.typeof(target)
if t.kind() == reflect.ptr { //指针类型获取真正type需要调用elem
t = t.elem()
}
newstruc := reflect.new(t)// 调用反射创建对象
newstruc.elem().fieldbyname("name").setstring("lily") //设置值
newval := newstruc.elem().fieldbyname("name") //获取值
fmt.println(newval.string())
}
补充:go语言中创建对象的几种方式
对于go对象
type car struct {
color string
size string
}
方式一:
使用t{…}方式,结果为值类型
c := car{}
方式二:
使用new的方式,结果为指针类型
c1 := new(car)
方式三:
使用&方式,结果为指针类型
c2 := &car{}
以下为创建并初始化
c3 := &car{"红色", "1.2l"}
c4 := &car{color: "红色"}
c5 := car{color: "红色"}
构造函数:
在go语言中没有构造函数的概念,对象的创建通常交由一个全局的创建函数来完成,以 newxxx 来命名,表示“构造函数” :
func newcar(color,size string)*car {
return &car{color,size}
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。
推荐阅读
