Home >Backend Development >Golang >Why Does Type Assertion Fail But Conversion Work with Custom Types in Go?

Why Does Type Assertion Fail But Conversion Work with Custom Types in Go?

Susan Sarandon
Susan SarandonOriginal
2024-11-04 08:41:30993browse

Why Does Type Assertion Fail But Conversion Work with Custom Types in Go?

Named Type Assertions and Conversions in Go

Consider the following scenario where a custom type is defined to redefine a pre-defined type:

<code class="go">type Answer string</code>

Now, let's attempt to use this custom type in a function that accepts the original pre-defined type:

<code class="go">func acceptMe(str string) {
    fmt.Println(str)
}

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

    // Type assertion fails
    acceptMe(ans.(string)) 
    // Conversion works
    acceptMe(string(ans))
}</code>

The type assertion ans.(string) fails with the error: invalid type assertion: ans.(string) (non-interface type Answer on left). On the other hand, the conversion string(ans) succeeds. This behavior raises the question:

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

To understand this, let's clarify that type assertions only work for interfaces. An interface can have arbitrary underlying types, making type assertions and type switches essential. Type assertions return a boolean value along with the result, indicating the success of the assertion.

In contrast, your custom type Answer has a fixed underlying type, which is string. Since you already know the exact types, you don't need type assertions because the conversion from Answer to string will always succeed. The syntax for this conversion is string(ans).

The above is the detailed content of Why Does Type Assertion Fail But Conversion Work with Custom Types in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn