duancilan5124 2017-01-22 20:06
浏览 30
已采纳

在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. 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条回答 默认 最新

  • dongxunhua2054 2017-01-22 20:55
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大