Type switch with slices

Hi there. I partly understand how type switch works. What I don’t understand is why I cannot treat the variable of the checked type as… well, as a variable of the checked type. Sorry, I know how it sounds, so let me show you an example. Consider this simple one, just to make the point, not to use it; the function Sum() here aims to calculate a sum of a slice, irrespective whether it’s a slice of float64s or ints. (Once more, I do not need such a function, I just want to understand why type switch works that way.)

package main

import (
	"fmt"
)

func Sum(X interface{}) interface{} {
	switch X.(type) {
	case []int:
		sum := 0
		for _, v := range X {
			sum += v
		}
		return sum
	case []float64:
		sum := float64(0)
		for _, v := range X {
			sum += v
		}
		return sum
	default:
		return 0
	}
}

func main() {
	fmt.Println(Sum([]int{0, 1}))
}

This does not work, since X is still treated as of interface{} type even though switch checks the type, and in our case it sees that the type is []int.

This basically means that I can check the type, but I cannot treat X as a variable of this type, right? Is there a way to get around this? I understand Go will soon get generics, and this will be the solution, but I hoped an approach similar to the above one could work. Since it does not, I am afraid type switch is not as useful as I initially thought. Or maybe it is, but I simply do not know how to do it?

You need to use a type switch that re-assigns:

switch x := X.(type) {
case []int:
  // use x
case []float64:
  // use x
default:
  return 0
}
2 Likes

Perfect! It’s working perfectly… Thanks a lot!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.