如果我有一个自定义类型,只需重新定义一个名称的预定义类型:
type Answer string
Run Code Online (Sandbox Code Playgroud)
我尝试在接受预定义类型的函数中使用它:
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))
}
Run Code Online (Sandbox Code Playgroud)
为什么类型断言失败,但转换工作?