命名类型断言和转换

命名类型断言和转换

本文介绍了去:命名类型断言和转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I have a custom type that simply redefines a pre-defined type with a name:

type Answer string

我尝试在接受预定义类型的函数中使用它:

And I try to use it in a function that accepts the pre-defined type:

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

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

Why does the type assertion fail, but the conversion work?

推荐答案

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

Type assertion works for interfaces only. Interface can have arbitrary underlying type, so we have type assertion and type switch to the rescue. Type assertion returns bool as the second return value to indicate if assertion was successful.

您的自定义类型 Answer 只能有一个基础类型。您已经知道确切的类型 - Answer 和基础类型 - string 。您不需要声明,因为转换为基础类型将始终成功。

Your custom type Answer can have only one underlying type. You already know the exact type - Answer and the underlying type - string. You don't need assertions, since conversion to the underlying type will always be successful.

只要将您的自定义类型转换为字符串即可。由于您的自定义类型具有 string 作为基础类型,所以转换将会成功。转换语法:string(ans)。

Just convert your custom type to string. The conversion will succeed since your custom type has string as an underlying type. The conversion syntax: string(ans). Go Play

这篇关于去:命名类型断言和转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 12:43