Home >Backend Development >Golang >Why Don\'t Type Assertions Work for Named Types in Go?
In Go, named type assertions are used to test whether a value implements a given interface. However, this approach doesn't directly apply to named types that redefine pre-defined types with a new name.
Consider the following code:
<code class="go">type Answer string func acceptMe(str string) { fmt.Println(str) } func main() { type Answer string var ans Answer = "hello" // Type assertion fails: acceptMe(ans.(string)) // Conversion to underlying type succeeds: acceptMe(string(ans)) }</code>
The type assertion ans.(string) fails because it attempts to check if the Answer type implements the string interface, which it doesn't. Instead, Answer is a custom type that redefines string.
On the other hand, the conversion string(ans) succeeds because it directly converts the Answer value to its underlying string type. Since Answer is a named type for string, this conversion is always valid.
Why doesn't the type assertion work for named types?
Type assertions are designed for interfaces. An interface can have multiple implementations (known as concrete types), and type assertions are used to check whether a value implements that interface. However, a named type has a fixed underlying type, which is known at compile time. Therefore, type assertions are unnecessary and cannot be performed for named types.
When to use conversion instead of type assertion?
Use conversion when you want to convert a named type to its underlying type. This is useful when you need to pass a value to a function or interface that expects a specific type but can accept its underlying type.
The above is the detailed content of Why Don\'t Type Assertions Work for Named Types in Go?. For more information, please follow other related articles on the PHP Chinese website!