Home > Backend Development > Golang > Why Am I Getting 'Cannot Type Switch on Non-Interface Value' in Go?

Why Am I Getting 'Cannot Type Switch on Non-Interface Value' in Go?

Patricia Arquette
Release: 2024-11-09 20:32:02
Original
742 people have browsed it

Why Am I Getting

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

While attempting to implement type assertion in Go, you may encounter the error message: "cannot type switch on non-interface value." This error arises when attempting to perform a type switch on a value that is not an interface 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 running this code, you will encounter the "cannot type switch on non-interface value" error. To resolve this, we need to cast the variable n to an interface{} type before performing the type switch.

switch v := interface{}(n).(type)
Copy after login

This cast converts the concrete type of n (*Number) to the interface type interface{}. Interfaces in Go act as a contract, allowing any value to be stored and accessed through common methods. By casting n to interface{}, we can then perform the type switch on the resulting interface value.

When we run the modified code, it will successfully print "Stringer: 1", as expected. This demonstrates that type assertion in Go requires the value to be an interface type, and casting to interface{} enables type switches on non-interface values.

The above is the detailed content of Why Am I Getting 'Cannot Type Switch on Non-Interface Value' 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template