Integer
and int
int
和你的新类型Integer
是两种不同的、不同的类型。在哪里Integer
预计,您必须传递类型的值Integer
.
如果你有一个Integer
value,您可以使用简单的类型转换使其成为 type 的值int
,因为底层类型Integer
is int
:
var i Integer = 5
nf(int(i))
同时可能令人困惑和有趣的是,您可以传递一个无类型常量而不进行转换:
nf(5)
尝试这些去游乐场 https://play.golang.org/p/M4w1kKmD9A.
其原因在于规格: 可分配性: https://golang.org/ref/spec#Assignability
A value x
is 可分配的 to a variable https://golang.org/ref/spec#Variables类型的T
("x
可分配给T
") 在任何这些情况下:
[...]
-
x
是一个无类型的constant https://golang.org/ref/spec#Constants可以用类型值表示T
.
5
是一个无类型常量,可由类型值表示int
因为无类型常量5
has a 默认类型 https://golang.org/ref/spec#Constants int
,所以它可以用类型的值表示Integer
(具有相同的默认类型)。
如果您检查其他可分配性规则(未包含在上面的引用中),它们都不符合您尝试传递值的情况Integer
对于类型参数int
,所以这是不允许的。
查看相关问题:Golang:创建常量类型并限制类型的值 https://stackoverflow.com/questions/37385007/golang-creating-a-constant-type-and-restricting-the-types-values/37386119#37386119
RuneFunc
and func(rune) rune
本例与上一例的区别(Integer
and int
) 就是它int
is a 命名类型 https://golang.org/ref/spec#Types and func(rune) rune
is not.
并且有一个可分配性规则允许这样做:
-
x
's type V
and T
有相同的底层类型 https://golang.org/ref/spec#Types并且至少其中之一V
or T
不是一个命名类型 https://golang.org/ref/spec#Types.
所以在这种情况下:
var f RuneFunc
ff(f)
f
是一个命名类型,但是参数类型ff()
is func(rune) rune
这是未命名的,因此允许分配。