英文:
Assignability of function parameters in golang
问题
type Boolean bool
func takes_bool(b bool) {
fmt.Printf("%t\n", b)
}
func takes_boolean(b Boolean) {
fmt.Printf("%t\n", b)
}
当我调用以下代码时:
takes_bool(Boolean(false))
takes_bool(Boolean(true))
我得到以下错误:
无法将Boolean(false)(类型为Boolean)用作函数参数中的bool类型
无法将Boolean(true)(类型为Boolean)用作函数参数中的bool类型
可赋值性规则似乎不禁止这样做,即至少一个不是命名类型,并且两者具有相同的基础类型:
type Boolean bool
vs
bool
英文:
type Boolean bool
func takes_bool(b bool) {
fmt.Printf("%t\n", b)
}
func takes_boolean(b Boolean) {
fmt.Printf("%t\n", b)
}
When I invoke the following:
takes_bool(Boolean(false))
takes_bool(Boolean(true))
I get:
cannot use Boolean(false) (type Boolean) as type bool in function argument
cannot use Boolean(true) (type Boolean) as type bool in function argument
The rules on assignability seems to NOT disallow it i.e. at least one is not a named type & both have the same underlying type:
type Boolean bool
vs
bool
答案1
得分: 2
在仔细阅读http://golang.org/ref/spec#Types后,我发现bool
被认为是一个命名类型(就像int
、float
和其他类型一样)。短语“未命名类型”只适用于类型字面量,比如interface{}
和struct{}
。
英文:
On a careful reading of http://golang.org/ref/spec#Types it seems bool
is considered a named type (as are int
and float
and friends). The phrase "unnamed types" only refer to type literals like interface{}
and struct{}
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论