Go: Named type assertions and conversions

huangapple go评论102阅读模式
英文:

Go: Named type assertions and conversions

问题

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

type Answer string

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

func acceptMe(str string) {
    fmt.Println(str)
}

func main() {
    type Answer string
    var ans Answer = "hello"

    // 无法将 ans (类型 Answer) 作为函数参数中的 string 类型使用
    acceptMe(ans)
    // 无效的类型断言:ans.(string)(左侧的非接口类型 Answer)
    acceptMe(ans.(string))
    // 这样可以工作,但我不明白为什么前面的方式不行:
    acceptMe(string(ans))
}

为什么类型断言失败,但类型转换却成功呢?

英文:

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?

答案1

得分: 22

类型断言只适用于接口。接口可以有任意的底层类型,所以我们有类型断言和类型切换来解决问题。类型断言返回一个布尔值作为第二个返回值,用于指示断言是否成功。

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

旧的答案:

只需将你的自定义类型转换为 string。转换将成功,因为你的自定义类型的底层类型是 string。转换语法:string(ans)。Go Play

英文:

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.

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.

Old answer:

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

huangapple
  • 本文由 发表于 2013年9月9日 13:25:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/18691927.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定