What\'s the Difference Between Type Assertions and Conversions for Custom Types in Go?

DDD
Release: 2024-11-06 10:32:02
Original
928 people have browsed it

What's the Difference Between Type Assertions and Conversions for Custom Types in Go?

Understanding the Differences Between Named Type Assertions and Conversions in Go

When working with custom types in Go, it's essential to understand the nuances between named type assertions and conversions. Let's explore the concept with an example.

Consider the code snippet below, where we define a custom type Answer that redefines the predefined string type:

<code class="go">type Answer string</code>
Copy after login

We then attempt to use Answer in a function that expects a string type:

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

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

    // Assertion fails: cannot use ans (type Answer) as type string in function argument
    acceptMe(ans)

    // Type assertion fails as well: invalid type assertion: ans.(string) (non-interface type Answer on left)
    acceptMe(ans.(string))

    // Conversion succeeds.
    acceptMe(string(ans))
}</code>
Copy after login

Why Do Assertions Fail?

Type assertions are only applicable to interfaces. Interfaces allow for underlying types to vary. To determine the actual type, Go uses type assertion (x.(T)) or type switch (switch x := x.(type)). The assertion returns a boolean value indicating if the assertion was successful.

In our case, Answer is a named type with a fixed underlying type (string). Since the underlying type is known, there's no need for assertions. Converting the Answer type to string using string(ans) is sufficient.

The above is the detailed content of What\'s the Difference Between Type Assertions and Conversions for 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template