2

Why isn't this a type mismatch?

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

A value x is assignable to a variable of type T ("x is assignable to T") in any of these cases: ...snip... x's type V and T have identical underlying types and at least one of V or T is not a named type. ...snip...

Is that because the underlying type of N[] is N[] which is not a named type?

What's the rationale behind it?

package main

import "fmt"

type N []N

func main() {
    n := make([]N, 1)
    fmt.Printf("%T\n", n)
    fmt.Printf("%T\n", n[0])
    n[0] = n
    //fmt.Println(n)
}

*Output:*
[]main.N
main.N
VM7
  • 45
  • 7

1 Answers1

1

You're asking if n[0] = n is valid. You've correctly identified the rule from the language spec:

A value x is assignable to a variable of type T ("x is assignable to T") in any of these cases:

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

And here's how it applies here:

  • n[0] has type N and underlying type []N (from the language specification: "the type to which N refers in its type declaration").
  • n has type []N (with the same underlying type).

So n[0] and n have identical underlying types ([]N), and the type of n is not a named type.

Paul Hankin
  • 54,811
  • 11
  • 92
  • 118
  • Do you know what the rationale is behind that rule? Besides confusing me of course. If I change n := make([]N, 1) to n := make(N, 1) why does that still work? I thought make needed a slice, map or channel. This is a bit off topic but also why does the following not give an out of bounds error. make([]int, 3)[3:] – VM7 Nov 08 '15 at 05:36
  • @VM7 I think it's an omission in the language spec that it doesn't say what `make(N, 1)` does. – Paul Hankin Nov 08 '15 at 06:46