【发布时间】:2017-01-23 04:55:26
【问题描述】:
我有两种结构类型
type type1 struct {
a1,b1,c1 string
}
type type2 struct {
a2,b2 string
}
如果条件为真,想要改变变量 p 的类型。我应该如何在 Go 中做到这一点?下面不起作用。我认为问题 'Golang : Is conversion between different struct types possible?' 没有解决这种情况,因为我收到错误 "cannot convert p .. cannot use type2 as type1 in assignment ...结构初始化程序中的值太多"
var p type1
if <condition> {
p = type2(p)
p = type2{"1","2"}
}
【问题讨论】:
-
现在不是重复的,无法将 type1 分配给 type2
-
根据我对go类型系统的蹩脚理解,p是type1,句号。在 if 条件之后,编译器如何知道 p 是什么类型?您能做的最好的事情就是分配字段。
-
你说的很有道理..没想到
-
然后我将其转换为实际答案。
标签: go type-conversion