How to Fix cannot type switch on non-interface value in Go

Go raises the “cannot type switch on non-interface value” error when you try to use a type switch on a value that is not an interface.

To fix the “cannot type switch on non-interface value” error, you must ensure that the value you use in the type switch is an interface. In Go, you can use a type switch to determine the concrete type of interface value at runtime.

Example

package main

import "fmt"

func main() {
  var value interface{}
  value = 21

  switch v := value.(type) {
    case int:
      fmt.Println("It's an int:", v)
    case string:
      fmt.Println("It's a string:", v)
    default:
      fmt.Printf("Unknown type: %T\n", v)
  }
}

In this example, value is an interface type, so using a type switch is valid.

If you try to use a type switch on a non-interface value, like an int or a string, you will get a compilation error.

package main

import "fmt"

func main() {
  var value int
  value = 42

  switch v := value.(type) { // This will cause a compilation error
    case int:
      fmt.Println("It's an int:", v)
    case string:
      fmt.Println("It's a string:", v)
    default:
      fmt.Printf("Unknown type: %T\n", v)
  }
}

Output

value (variable of type int) is not an interface

To fix this error, you must use an interface type for the value you’re checking in the type switch.

If you have a non-interface value and need to perform a type switch, you can first assign it to an empty interface variable:

package main

import "fmt"

func main() {
  var intValue int
  intValue = 21

  var value interface{}
  value = intValue

  switch v := value.(type) {
    case int:
      fmt.Println("It's an int:", v)
    case string:
      fmt.Println("It's a string:", v)
    default:
      fmt.Printf("Unknown type: %T\n", v)
  }
}

Output

It's an int: 21

You can use the type switch without issues by assigning the intValue to an empty interface variable value.

That’s it.

Leave a Comment