Mar 8, 2019

[Go] conversion rule

Conversion rules:

Since Golang 1.7
A non-constant value x can be converted to type T in any of these cases:
  • same sequence of fields (order matters due to memory layout, in C/C++/assembly/Golang, which includes padding.
    In C++, padding matters also due to object slicing (hey, we have inheritance in C++).
    Please refer to note:
    http://vsdmars.blogspot.com/2018/09/golangc-padding.html)
  • corresponding fields with same type.
  • 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.
  • ignoring struct tags, x's type and T have identical underlying types.
  • ignoring struct tags, x's type and T are unnamed pointer types and their pointer base types have identical underlying types.

type Person struct {
    Name     string
    AgeYears int
    SSN      int
}

var aux struct {
    Name     string `json:"full_name"`
    AgeYears int    `json:"age"`
    SSN      int    `json:"social_security"`
}

var yeah Person = Person(aux)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.