相关疑难解决方法(0)

Go:命名类型断言和转换

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

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)

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

go

14
推荐指数
1
解决办法
1万
查看次数

标签 统计

go ×1