Jun 22, 2018

[Go] type conversion

Unlike C++ strong type language it's hard to convert from different type name even they have the same memory layout, we can convert; however, through ptr. golang spec: https://golang.org/ref/spec#Assignability
package main

import (
 "fmt"
)

type type1 []struct {
    Field1 string
    Field2 int
}
type type2 []struct {
    Field1 string
    Field3 int // conversion must have same name. Why? Due to accessing the datamember name should be consistent.
}

func main() {
 t1 := type1{{"A", 1}, {"B", 2}}
 t2 := type2(t1)
 fmt.Println(t2)
}

No comments:

Post a Comment

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