今天下午小明在修改某个工程时候遇到不同的protbuf生成的结构体需要相互赋值不想分字段赋值转换的问题,小明拥有多年c++经验但是对go只能算作入门,虽然我也做了好几年go的开发但并没有深入探究过,盲猜了下肯定是可以通过类型转换实现相互赋值的。“talk is cheap,show me the code”,于是在本机编写了个简易工程进行验证:
func main() {
a := A{}
a.name = "xx-a"
a.id = "id-a"
fmt.Printf("a addr: %p \n", &a)
nb := B(a)
fmt.Println("nb :", nb)
fmt.Printf("nb addr: %p \n", &nb)
aa := new(A)
aa.name = "new-a-name"
aa.id = "new-a-id"
fmt.Println("*aa :", *aa)
fmt.Println("aa :", aa)
fmt.Printf("aa address: %p\n", aa)
bb := new(B)
bb = (*B)(aa)
fmt.Println("*bb:", *bb)
fmt.Println("bb :", bb)
fmt.Printf("bb address: %p\n", bb)
}
type A struct {
name string
id string
}
type B struct {
name string
id string
}
参考了万能的stackoverflow开始用nb := B(a)的方式可以顺利赋值,后来小明说指针强制类型转换肯定可以,于是采用bb = (*B)(aa)进行验证,运行结果如下:
a addr: 0xc000098420
nb : {xx-a id-a}
nb addr: 0xc000098460
*aa : {new-a-name new-a-id}
aa : &{new-a-name new-a-id}
aa address: 0xc0000984a0
*bb: {new-a-name new-a-id}
bb : &{new-a-name new-a-id}
bb address: 0xc0000984a0
第一种方式,相当于把A 中的字段逐一给赋值给B,第二种方式直接进行内存交换指向,aa 和bb 拥有相同的地址,强制将aa的地址转为bb的地址;上述两种方式均可,采用第二种更加节省内存,只是不大好理解; 参考:Golang : Is conversion between different struct types possible? golang-conversion-between-structs
本文链接:https://iokde.com/post/golang-conversion-between-structs.html,参与评论 »
--EOF--
发表于 2021-07-12 18:15:00,并被添加「golang」标签。
本站使用「署名 4.0 国际」创作共享协议,转载请注明作者及原网址。tools更多说明 »
提醒:本文最后更新于 1057 天前,文中所描述的信息可能已发生改变,请谨慎使用。
Comments