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

Susan Sarandon
Release: 2024-11-04 08:41:30
Original
870 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!