Check assignability and conversions
Check assignability and conversions
Assignment places a value into a destination of a compatible type. Identical types are assignable; identical underlying types can also permit assignment when at least one type is not named and neither is a type parameter. Other rules cover interfaces, channels, nil and representable untyped constants. An explicit conversion uses T(x) and has its own rules.
package main
import ( "fmt")
type IDs []inttype Scores []int
func main() { var a IDs = []int{2, 4} var b []int = a c := Scores(a) c[0] = 9 fmt.Println(a[0], b[0], c[0])}Assignment between IDs and unnamed []int is valid. Scores and IDs are distinct named types, so use a conversion. The slice values still share backing storage; converting types does not inherently clone data.
Expected output:
9 9 9Convert matching structs with different tags
package main
import ( "fmt")
func main() { a := struct { N int `a:"n"` }{N: 7} b := struct { N int `b:"n"` }(a) fmt.Println(b.N) x := 257 fmt.Println(uint8(x))}Struct conversion may ignore tags when checking otherwise identical underlying types. Direct assignment is not valid for these distinct unnamed structs. Runtime integer conversion can discard high bits: 257 becomes 1 in uint8. Check the range first if preserving the value matters.
Expected output:
71Try it locally
Define Meter int and Count int, initialize Meter with 12, convert it to Count and print its type and value.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Advanced type semantics 02: Check assignability and conversions
Check the lesson objective before moving on.
Does converting a slice to a different defined slice type clone its array?
Which can convert between otherwise identical structs with different tags?