1

The following code works just fine:

type alias []byte

type data struct {
    x alias
}

func main() {
    s2 := []byte("s2")
    s1 := &data{
        x: s2,
    }
    var s4 alias = s2
    fmt.Println(s1,s2, s4)
}

but the following doesn't compile

type alias string

type data struct {
    x alias
}

func main() {
    s2 := string("s2")
    s1 := &data{
        x: s2, // needs explicit alias(s2)
    }
    var s4 alias = s2 // needs explicit alias(s2)
    fmt.Println(s1,s2, s4)
}
}

The only difference is the type alias changes from a slice of bytes to a string.

What's the difference between those types, that the one is auto-converted and the other is not?

Martin Rauscher
  • 1,700
  • 1
  • 14
  • 20
  • 6
    Note that these are not type aliases. See the [Assignability](https://golang.org/ref/spec#Assignability) section in the spec. – JimB Oct 20 '20 at 16:58
  • 2
    (also, if you do use a type alias, you can assign them directly, because they are the same type:https://play.golang.org/p/bJmbWZt-muE) – JimB Oct 20 '20 at 17:14
  • Thanks, yes, they are "type definitions". But the rule with "at least one of V or T is not a defined type" is not quite intuitive... – Martin Rauscher Oct 21 '20 at 19:43

1 Answers1

9

According to the Go langauge spec:

https://golang.org/ref/spec#Assignability

This specific clause:

x's type V and T have identical underlying types and at least one of V or T is not a defined type.

And note that, string is a defined type and []byte is an undefined type. So:

  • You can assign a []byte to alias because they have identical underlying types, and []byte is an undefined type
  • You cannot assign a string to alias because they are both defined types.
Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
  • Also `string` isn't just `type string []byte`, they are treated differently by the compiler. Strings are immutable, byte slices are not; and while you can convert freely between `string` and `[]byte`, `range` on a `string` produces `rune` elements, not `byte`s. – Adrian Oct 20 '20 at 19:58