为什么这个赋值没有类型不匹配的错误?

huangapple go评论85阅读模式
英文:

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 的类型 VT 具有相同的基础类型,并且 VT 中至少有一个不是命名类型。

以下是它在这里的应用:

  • 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 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.

huangapple
  • 本文由 发表于 2015年11月8日 11:25:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/33590399.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定