Golang中函数参数的可赋值性

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

Assignability of function parameters in golang

问题

在playground上运行

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
英文:

Runnable on playground

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被认为是一个命名类型(就像intfloat和其他类型一样)。短语“未命名类型”只适用于类型字面量,比如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{}.

huangapple
  • 本文由 发表于 2014年4月9日 05:16:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/22948349.html
匿名

发表评论

匿名网友

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

确定