change struct type in Go

huangapple go评论72阅读模式
英文:

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 &lt;condition&gt; {
		p = type2(p)
		p = type2{&quot;1&quot;,&quot;2&quot;}
	} 

答案1

得分: 2

不可能的。

根据我对Go类型系统的肤浅理解,ptype1,没有疑问。编译器怎么会知道在 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.

huangapple
  • 本文由 发表于 2017年1月23日 04:06:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/41795589.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定