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>
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>
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!