【问题标题】:Go: Named type assertions and conversionsGo:命名类型断言和转换
【发布时间】:2013-09-09 05:25:25
【问题描述】:

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

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))
}

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

【问题讨论】:

    标签: go


    【解决方案1】:

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

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

    旧答案:

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

    【讨论】:

    • 谢谢,在您回答问题时,我也发现了这一点。我想知道为什么会这样。
    • Ups :) 更新了答案。 > // 有效,但我不明白为什么如果前一个没有。类型断言和类型转换是正交的事情。类型断言仅适用于接口。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-27
    • 2014-01-08
    • 2016-12-13
    • 1970-01-01
    • 2014-01-22
    • 2014-01-12
    • 1970-01-01
    相关资源
    最近更新 更多