Home > Backend Development > Golang > Why Does a Type Switch with Multiple Cases in Go Cause 'undefined' Variable Errors, and How Can This Be Resolved?

Why Does a Type Switch with Multiple Cases in Go Cause 'undefined' Variable Errors, and How Can This Be Resolved?

Mary-Kate Olsen
Release: 2024-12-16 10:53:11
Original
306 people have browsed it

Why Does a Type Switch with Multiple Cases in Go Cause

Type Switch with Multiple Cases in Go

When using a type switch with multiple cases, one may encounter an error stating that a variable in a case with multiple types is undefined. This behavior stems from the Go language specification, which dictates that a type switch guard may include a short variable declaration.

In such cases, the variable has the same type as the type listed in single-type cases. However, in cases with a listing of multiple types, the variable has the type of the expression in the type switch guard.

To illustrate this, consider the following code:

type A struct {
  a int
}

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

type B struct {
  A
}

var foo interface{}
foo = A{}

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

Running this code will result in the error "a.test undefined (type interface {} is interface with no methods)." This is because the variable a has the type interface{}, not the type of the specific case.

To resolve this issue, one can assert that the type switch guard expression has the expected method. For instance:

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

This code first checks if foo has the test() method, and if it does, it assigns the value of foo to a and calls the test() method.

The above is the detailed content of Why Does a Type Switch with Multiple Cases in Go Cause 'undefined' Variable Errors, and How Can This Be Resolved?. 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