gpt4 book ai didi

Go:命名类型断言和转换

转载 作者:IT老高 更新时间:2023-10-28 13:05:42 38 4
gpt4 key购买 nike

如果我有一个自定义类型,它只是重新定义了一个带有名称的预定义类型:

type Answer string

我尝试在接受预定义类型的函数中使用它:

func acceptMe(str string) {
fmt.Println(str)
}

func main() {
type Answer string
var ans Answer = "hello"

// cannot use ans (type Answer) as type string in function argument
acceptMe(ans)
// invalid type assertion: ans.(string) (non-interface type Answer on left)
acceptMe(ans.(string))
// Does work, but I don't understand why if the previous doesn't:
acceptMe(string(ans))
}

为什么类型断言失败,但转换工作?

最佳答案

类型断言仅适用于接口(interface)。接口(interface)可以有任意的底层类型,所以我们有类型断言和类型切换来救援。类型断言返回 bool 作为第二个返回值,表示断言是否成功。

您的自定义类型 Answer 只能有一种基础类型。您已经知道确切的类型 - Answer 和基础类型 - string。您不需要断言,因为转换为基础类型总是成功的。

旧答案:

只需将您的自定义类型转换为 string。转换将成功,因为您的自定义类型具有 string 作为基础类型。转换语法:string(ans)。 Go Play

关于Go:命名类型断言和转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18691927/

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