如果我有一个自定义类型,它只是重新定义了一个带有名称的预定义类型:
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))
}
为什么类型断言失败,但转换工作?