Assignability of composite components

September 21, 2023

Composite literals

… The types of the elements and keys must be [assignable(] to the respective field, element, and key types of type T; there is no additional conversion.

This shouldn’t be surprising, but let’s examine the implications just the same.

type myStr string

s := myStr("my string")

var x = map[int]string{
  3:         "oink",     // Valid, untyped numeric constant 3 is assignable to an int.
  int(4):    "quack",    // Valid, int(4) is of type int
  int64(12): "moo",      // Invalid, int64(12) is not converted to int
  8:         s,          // Invalid, type myStr is type string
  9:         string(s),  // Valid; explicit conversion to type string

Quotes from The Go Programming Language Specification Version of August 2, 2023

Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .