Golang 底层类型
Golang underlying types
在规范的这段代码中
type T1 string
type T2 T1
type T3 []T1
type T4 T3
规范说:
The underlying type of string, T1
, and T2
is string
.
The underlying type of []T1
, T3
, and T4
is []T1
.
为什么T2
的底层类型不是T1
,而是string
?
T4
的基础类型不应该是 []string
而不是 []T1
如果 T1
的基础类型是 string
吗?
困惑。
Each type T
has an underlying type: If T
is one of the predeclared boolean, numeric, or string types, or a type literal, the corresponding underlying type is T
itself.
Otherwise, T
's underlying type is the underlying type of the type to which T
refers in its type declaration.
T2
在其类型声明中引用 T1
,它具有基础类型 string
.
T2
的基础类型为 string
很重要,因为它有助于 Assignability 其中
A value x is assignable to a variable of type T ("x is assignable to T")
x's type V and T have identical underlying types and at least one of V or T is not a named type.
这在“Golang: Why can I type alias functions and use them without casting?”
中也有详细说明
说到T4
的底层类型,我们说的是底层未命名类型[]T1
。
再一次,可分配性规则表明您可以将 []T1
分配给 T4(因为 []T1
不是命名类型):它的基础类型停止在第一个未命名类型([]T1
).
var t3 T3 = []T1{"a", "b"}
fmt.Println("t3='%+v'", t3)
// var t4 T4 = []string{}
// cannot use []string literal (type []string) as type T4 in assignment
var t4 T4 = T4(t3)
fmt.Println("t4='%+v'", t4)
t4 = []T1{T1("c"), T1("d")}
fmt.Println("t4='%+v'", t4)
输出:
t3='%+v' [a b]
t4='%+v' [a b]
t4='%+v' [c d]
在规范的这段代码中
type T1 string
type T2 T1
type T3 []T1
type T4 T3
规范说:
The underlying type of string,
T1
, andT2
isstring
.
The underlying type of[]T1
,T3
, andT4
is[]T1
.
为什么T2
的底层类型不是T1
,而是string
?
T4
的基础类型不应该是 []string
而不是 []T1
如果 T1
的基础类型是 string
吗?
困惑。
Each type
T
has an underlying type: IfT
is one of the predeclared boolean, numeric, or string types, or a type literal, the corresponding underlying type isT
itself.
Otherwise,T
's underlying type is the underlying type of the type to whichT
refers in its type declaration.
T2
在其类型声明中引用 T1
,它具有基础类型 string
.
T2
的基础类型为 string
很重要,因为它有助于 Assignability 其中
A value x is assignable to a variable of type T ("x is assignable to T")
x's type V and T have identical underlying types and at least one of V or T is not a named type.
这在“Golang: Why can I type alias functions and use them without casting?”
中也有详细说明说到T4
的底层类型,我们说的是底层未命名类型[]T1
。
再一次,可分配性规则表明您可以将 []T1
分配给 T4(因为 []T1
不是命名类型):它的基础类型停止在第一个未命名类型([]T1
).
var t3 T3 = []T1{"a", "b"}
fmt.Println("t3='%+v'", t3)
// var t4 T4 = []string{}
// cannot use []string literal (type []string) as type T4 in assignment
var t4 T4 = T4(t3)
fmt.Println("t4='%+v'", t4)
t4 = []T1{T1("c"), T1("d")}
fmt.Println("t4='%+v'", t4)
输出:
t3='%+v' [a b]
t4='%+v' [a b]
t4='%+v' [c d]