英文:
change struct type in Go
问题
我有两种结构类型:
type type1 struct {
a1, b1, c1 string
}
type type2 struct {
a2, b2 string
}
如果条件为真,我想要改变变量p的类型。在Go语言中,我应该如何做?下面的代码是不起作用的。我认为问题**'Golang: 是否可以在不同的结构类型之间进行转换?'*并没有解决这个情况,因为我得到了错误信息"cannot convert p .. cannot use type2 as type1 in assignment ...too many values in struct initializer"*。
var p type1
if <condition> {
p = type2(p)
p = type2{"1", "2"}
}
请注意,我只会返回翻译好的部分,不会回答关于翻译的问题。
英文:
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. How I am supposed to do it in Go ? Below does not work. And I think the question 'Golang : Is conversion between different struct types possible?' 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"
var p type1
if <condition> {
p = type2(p)
p = type2{"1","2"}
}
答案1
得分: 2
不可能的。
根据我对Go类型系统的肤浅理解,p 是 type1,没有疑问。编译器怎么会知道在 if 条件之后 p 的类型是什么呢?你能做的最好的办法就是给字段赋值。
英文:
Not possible.
According to my lame understanding of go type system, p is type1, period. How the compiler would know what type is p after the if condition? The best you can do is to assign the fields.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论