Golang无法在将隐式类型的常量赋值给变量时进行检测。

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

Golang not able to detect implicitly typed const when assigning to a variable

问题

当我尝试将一个隐式类型的常量赋值给一个变量时,被赋值的变量无法检测到自定义类型,而是被赋值为底层的原始类型。例如:

type Custom string
const (
    First Custom = "10"
    Second = "20"
)

func SomeFunc(x Custom) {
    fmt.Printf("Inside func %v %v", x, reflect.TypeOf(x))
}

out := Second
SomeFunc(out)

会报错:

cannot use out (type string) as type Custom in argument to SomeFunc

然而 SomeFunc(Second) 是可以正常工作的。

另外,

fmt.Printf("%v %v\n", reflect.TypeOf(second), reflect.TypeOf(out)) //prints string string

这段代码会输出 string string

你可以在这里找到一个可以复现这个问题的示例:https://play.golang.org/p/Iv-C1ee992

有人可以帮助我理解这里发生了什么吗?

英文:

When I try to assign an implicitly typed constant to a variable, the assigned variable doesn't detect the custom type and instead gets assigned as the underlying primitive type. i.e;
For:

type Custom string
const (
    First Custom = "10"
    Second = "20"
)

If I have a function:

func SomeFunc( x Custom) {
	fmt.Printf("Inside func %v %v", x, reflect.TypeOf(x))
}

Then when I:

out := Second
SomeFunc(out)

it errors with:
> cannot use out (type string) as type Custom in argument to SomeFunc

However SomeFunc(Second) works fine.

Also

fmt.Printf("%v %v\n",reflect.TypeOf(second),reflect.TypeOf(out)) //prints string string

Here is the reproducer: https://play.golang.org/p/Iv-C1ee992

Can someone help me understand what is happening here?

答案1

得分: 3

Second是一个无类型的常量,并具有以下属性(https://blog.golang.org/constants):

无类型常量只是一个值,尚未被赋予定义的类型,这将迫使它遵守严格的规则,防止组合不同类型的值。
...
将它们分配给与字符串兼容的任何类型的变量都可以正常工作,不会出错。

相反,out是一个字符串类型的变量。再次引用博文中的内容:

现在你可能会问,“如果常量是无类型的,那么在这个变量声明中,str是如何获得类型的?”答案是,无类型常量有一个默认类型,即如果需要类型而没有提供类型时,它会隐式地将其转换为一个值。对于无类型字符串常量,显然默认类型是字符串。

英文:

Second is an untyped const and has this property (https://blog.golang.org/constants):

> An untyped constant is just a value, one not yet given a defined type
> that would force it to obey the strict rules that prevent combining
> differently typed values.
...
> Assigning them to a variable of any type compatible with strings works
> without error.

On the contrary out is a variable of type string. Again from the blog post:

> and by now you might be asking, "if the constant is untyped, how does
> str get a type in this variable declaration?" The answer is that an
> untyped constant has a default type, an implicit type that it
> transfers to a value if a type is needed where none is provided. For
> untyped string constants, that default type is obviously string

huangapple
  • 本文由 发表于 2017年5月9日 00:00:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/43852232.html
匿名

发表评论

匿名网友

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

确定