Golang : Is conversion between different struct types possible?

前端 未结 5 838
小蘑菇
小蘑菇 2020-12-01 00:17

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

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


        
5条回答
  •  天命终不由人
    2020-12-01 00:22

    To give a reference to OneOfOne's answer, see the Conversions section of the spec.

    It states that

    A non-constant value x can be converted to type T in any of these cases:

    • x is assignable to T.
    • x's type and T have identical underlying types.
    • x's type and T are unnamed pointer types and their pointer base types have identical underlying types.
    • x's type and T are both integer or floating point types.
    • x's type and T are both complex types.
    • x is an integer or a slice of bytes or runes and T is a string type.
    • x is a string and T is a slice of bytes or runes.

    The first and highlighted case is your case. Both types have the underlying type

    []struct { Field1 string Field2 int }
    

    An underlying type is defined as

    If T is one of the predeclared boolean, numeric, or string types, or a type literal, the corresponding underlying type is T itself. Otherwise, T's underlying type is the underlying type of the type to which T refers in its type declaration. (spec, Types)

    You are using a type literal to define your type so this type literal is your underlying type.

提交回复
热议问题