如果我有一个自定义类型,只是简单地用名称重新定义了一个预定义类型:
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))
}
为什么类型断言失败,但转换有效?
发布于 2013-09-09 13:35:24
类型断言仅适用于接口。接口可以有任意的底层类型,所以我们有类型断言和类型切换来拯救。类型断言返回bool
作为第二个返回值,以指示断言是否成功。
您的自定义类型Answer
只能有一个基础类型。您已经知道了确切的类型- Answer
和底层类型- string
。您不需要断言,因为到底层类型的转换总是成功的。
老生常谈:
只需将您的自定义类型转换为string
。由于您的自定义类型将string
作为基础类型,因此转换将会成功。转换语法:字符串(Ans)。Go Play
https://stackoverflow.com/questions/18691927
复制相似问题