ds42774 2017-05-08 16:00
浏览 116
已采纳

Golang在分配给变量时无法检测隐式类型的const

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
",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条回答 默认 最新

  • dpepbjp126917 2017-05-08 16:10
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题