Home > Backend Development > Golang > How to Correctly Use Multiple Cases in Go's Type Switch to Avoid Method Errors?

How to Correctly Use Multiple Cases in Go's Type Switch to Avoid Method Errors?

Barbara Streisand
Release: 2024-12-18 10:37:10
Original
198 people have browsed it

How to Correctly Use Multiple Cases in Go's Type Switch to Avoid Method Errors?

Type Switch with Multiple Cases

In Go, a type switch statement can be used to dynamically select a corresponding case based on the type of a value. When multiple types are specified in a single case, an error may be raised if the type of the value does not match any of the listed types.

Consider the following code snippet:

package main

import (
    "fmt"
)

type A struct {
    a int
}

func(this *A) test(){
    fmt.Println(this)
}

type B struct {
    A
}

func main() {
    var foo interface{}
    foo = A{}
    switch a := foo.(type){
        case B, A:
            a.test()
    }
}
Copy after login

When this code is run, it produces the following error:

a.test undefined (type interface {} is interface with no methods)
Copy after login

This error indicates that the type switch did not take effect because the variable a has the type interface{}, which does not have the test() method.

The Go language specification explains that in a type switch statement, when multiple types are specified in a case, the variable declared in that case will have the type of the expression in the type switch guard (in this case, foo). Since foo is of type interface{}, a also becomes an interface{} type.

To resolve this issue and ensure that the test() method can be called, you can explicitly assert that foo has the test() method before performing the type switch, like so:

package main

import (
    "fmt"
)

type A struct {
    a int
}

func (this *A) test() {
    fmt.Println(this)
}

type B struct {
    A
}

type tester interface {
    test()
}

func main() {
    var foo interface{}
    foo = &B{}
    if a, ok := foo.(tester); ok {
        fmt.Println("foo has test() method")
        a.test()
    }
}
Copy after login

By asserting that foo has the test() method, you can retrieve a value of the appropriate type and call the test() method successfully.

The above is the detailed content of How to Correctly Use Multiple Cases in Go's Type Switch to Avoid Method Errors?. 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