键入与未键入的常量

Go 中的常量可以是键入的或非类型的。例如,给定以下字符串文字:

"bar"

有人可能会说文字的类型是 string,但是,这在语义上并不正确。相反,文字是 Untyped 字符串常量。它是一个字符串(更准确地说,它的默认类型string),但它不是 Go ,因此在键入的上下文中分配或使用它之前没有类型。这是一个微妙的区别,但是一个有用的理解。

同样,如果我们将文字分配给常量:

const foo = "bar"

它保持无类型,因为默认情况下,常量是无类型的。也可以将它声明为类型化的字符串常量

const typedFoo string = "bar"

当我们尝试在具有类型的上下文中分配这些常量时,差异就会发挥作用。例如,请考虑以下事项:

var s string
s = foo      // This works just fine
s = typedFoo // As does this

type MyString string
var mys MyString
mys = foo      // This works just fine
mys = typedFoo // cannot use typedFoo (type string) as type MyString in assignment