上面我们提到 go 仅仅支持常量拥有不确定类型,所以即使变量 name 没有申明类型,但编译器会根据右边的值推测出一个具体的类型赋给 name, 这里 "Golang" 的类型是 UntypedString。UntypedString 只能被转换为 string 类型,所以对 alias 的赋值会报错。
// BasicKind describes the kind of basic type.
type BasicKind int
const (
Invalid BasicKind = iota // type is invalid
// predeclared types
Bool
// ... 省略其它类型
Int8
Complex128
String
UnsafePointer
// types for untyped values
UntypedBool
UntypedInt
UntypedRune
UntypedFloat
UntypedComplex
UntypedString
UntypedNil
// aliases
Byte = Uint8
Rune = Int32
)
var a int16
var b int32
c := a + b // 错误信息:invalid operation: mismatched types int16 and int32
int a = 10;
float b = 1.0f;
String c = "Java";
String d = a + b + c;
const name string = "Golang"
const name string = 1.2 // 错误信息:cannot convert 1.2(untyped float constant) to string
const name = "Golang"
const alias string = name
type Str string
const name = "Golang"
const alias Str = name
const owner string = "google"
const ownerAlias Str = owner // 错误信息:cannot use owner (constant "google" of type string) as Str value in constant declaration
type Str string
var name = "Golang"
var alias Str = name // 错误信息:cannot use name (variable of type string) as Str value in variable declaration