Why Do I Get the 'Cannot Type Switch on Non-Interface Value' Error in Golang?

Susan Sarandon
Release: 2024-11-13 04:40:02
Original
910 people have browsed it

Why Do I Get the

Error: "Cannot Type Switch on Non-Interface Value" in Golang

When working with type assertions, you may encounter the error "cannot type switch on non-interface value." This occurs when attempting to perform a type switch on a value that is not an interface.

In Golang, type switching allows you to conditionally execute code based on the type of a variable. However, it requires the variable to be of an interface type. An interface represents a contract that defines a set of methods that an implementing type must implement.

In the provided code snippet, a type named Stringer is defined with a single String() method. The Number type also implements the String() method, making it a concrete implementation of the Stringer interface.

type Stringer interface {
    String() string
}

type Number struct {
    v int
}

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

However, the error occurs in the main function, where a type switch is attempted on the n variable, which is of type *Number rather than Stringer.

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

To resolve this issue, you need to cast n to interface{} before performing the type assertion. This is because interface{} can represent any arbitrary value.

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

By casting n to interface{}, you essentially allow the type switch to consider the possibility that n might be of type Stringer. Once the type switch is entered, the actual type of n can be determined and the appropriate case branch executed.

The above is the detailed content of Why Do I Get the 'Cannot Type Switch on Non-Interface Value' Error in Golang?. 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