Type Assertion in Go: Why 'Cannot Type Switch on Non-Interface Value' and How to Fix?

Susan Sarandon
Release: 2024-11-13 10:56:02
Original
414 people have browsed it

Type Assertion in Go: Why

Type Assertion in Go: Resolving the "Cannot Type Switch on Non-Interface Value" Error

When working with type assertions in Go, it's possible to encounter the error "cannot type switch on non-interface value." Let's delve into what this means and how to resolve it, with an example using a custom type.

Consider the following code snippet:

package main

import "fmt"
import "strconv"

type Stringer interface {
    String() string
}

type Number struct {
    v int
}

func (number *Number) String() string {
    return strconv.Itoa(number.v)
}

func main() {
    n := &Number{1}
    switch v := n.(type) {
    case Stringer:
        fmt.Println("Stringer:", v)
    default:
        fmt.Println("Unknown")
    }
}
Copy after login

When you run this code, you'll encounter the error "cannot type switch on non-interface value." This indicates that the type assertion is being performed on a non-interface value. In this case, n is a pointer to a Number struct, which is not an interface.

The solution is to cast the value to an interface{} before attempting the type assertion. This is because type assertions can only be performed on interface values. Here's the corrected code:

func main() {
    n := &Number{1}
    switch v := interface{}(n).(type) {
    case Stringer:
        fmt.Println("Stringer:", v)
    default:
        fmt.Println("Unknown")
    }
}
Copy after login

Now, when you run the code, it will print "Stringer: 1." This is because casting n to interface{} allows it to be treated as an interface value for type assertion.

The above is the detailed content of Type Assertion in Go: Why 'Cannot Type Switch on Non-Interface Value' and How to Fix?. 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