如何将基类型转换为继承它的类型



假设我有

type Tags []string

我有生成[]string:的代码

b := []string{"hello", "world"}

如何获得b,使其类型为Tags而不是[]string

使用显式类型转换:

b := Tags([]string{"hello", "world"})
fmt.Printf("%Tn", b)

哪个输出:

main.Tags

但您也可以在复合文字中直接使用Tags作为类型:

b2 := Tags{"hello", "world"}
fmt.Printf("%Tn", b2)

再次输出:

main.Tags

试试围棋场上的例子。

最新更新