Reputation: 45
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
Upvotes: 2
Views: 2141
Reputation: 58409
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 typeT
("x
is assignable toT
") in any of these cases:
- ...
x
's typeV
andT
have identical underlying types and at least one ofV
orT
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.
Upvotes: 1