英文:
Why isn't this assignment a type mismatch?
问题
为什么这不是类型不匹配的情况?
来自:https://golang.org/ref/spec#Assignability
在以下任何情况下,值x都可以分配给类型为T的变量("x可以分配给T"):
...省略...
x的类型V和T具有相同的基础类型,并且V或T中至少有一个不是命名类型。
...省略...
这是因为N[]的基础类型是N[],而N[]不是命名类型吗?
这背后的原理是什么?
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)
}
*输出:*
[]main.N
main.N
英文:
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
答案1
得分: 1
你正在询问 n[0] = n
是否有效。你正确地从语言规范中找到了规则:
在以下情况下,值
x
可以赋给类型为T
的变量(“x
可以赋给T
”):
- ...
x
的类型V
和T
具有相同的基础类型,并且V
或T
中至少有一个不是命名类型。
以下是它在这里的应用:
n[0]
的类型是N
,基础类型是[]N
(来自语言规范:“N
在其类型声明中引用的类型”)。n
的类型是[]N
(具有相同的基础类型)。
因此,n[0]
和 n
具有相同的基础类型([]N
),且 n
的类型不是命名类型。
英文:
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 typeN
and underlying type[]N
(from the language specification: "the type to whichN
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论