[英]change struct type in Go
I have two struct types我有两种结构类型
type type1 struct {
a1,b1,c1 string
}
type type2 struct {
a2,b2 string
}
and want to change type of variable p if the condition is true.并希望在条件为真时更改变量 p 的类型。 How I am supposed to do it in Go ?
我应该如何在 Go 中做到这一点? Below does not work.
下面不起作用。 And I think the question 'Golang : Is conversion between different struct types possible?'
我认为“Golang:不同结构类型之间的转换可能吗?”这个问题。 does not address this case because I am getting error "cannot convert p .. cannot use type2 as type1 in assignment ...too many values in struct initializer"
没有解决这种情况,因为我收到错误“无法转换 p .. 不能在赋值中使用 type2 作为 type1 ......结构初始值设定项中的值太多”
var p type1
if <condition> {
p = type2(p)
p = type2{"1","2"}
}
Not possible.不可能。
According to my lame understanding of go type system, p is type1 , period.根据我对 go 类型系统的蹩脚理解, p是type1 ,句号。 How the compiler would know what type is p after the if condition?
编译器如何知道在if条件之后p是什么类型? The best you can do is to assign the fields.
您能做的最好的事情就是分配字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.