Go: Named type assertions and conversions

后端 未结 1 1845
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-30 05:00

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 acc

1条回答
  •  無奈伤痛
    2020-12-30 05:25

    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

    0 讨论(0)
提交回复
热议问题