gpt4 book ai didi

types - Golang 底层类型

转载 作者:IT王子 更新时间:2023-10-29 01:39:38 27 4
gpt4 key购买 nike

在规范中的这段代码中

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 ?
困惑。

最佳答案

spec mentions :

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)。

参见 this example on playground

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]

关于types - Golang 底层类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29332879/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com