duancilan5124 2014-07-07 14:40
浏览 854
已采纳

Golang:不同结构类型之间是否可以转换?

Let's say I have two similar types set this way :

type type1 []struct {
    Field1 string
    Field2 int
}
type type2 []struct {
    Field1 string
    Field2 int
}

Is there a direct way to write values from a type1 to a type2, knowing that they have the same fields ? (other than writing a loop that will copy all the fields from the source to the target)

Thanks.

  • 写回答

6条回答 默认 最新

  • doupi6737 2014-07-07 14:46
    关注

    For your specific example, you can easily convert it <kbd>playground</kbd>:

    t1 := type1{{"A", 1}, {"B", 2}}
    t2 := type2(t1)
    fmt.Println(t2)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?