I'm noob in Go :) so my question may be stupid, but can't find answer, so.
I need a function:
func name (v interface{}) {
if is_slice() {
for _, i := range v {
my_var := i.(MyInterface)
... do smth
}
} else {
my_var := v.(MyInterface)
... do smth
}
}
How can I do is_slice
in Go? Appreciate any help.
In your case the type switch is the simplest and most convenient solution:
The
case
branches enumerate the possible types, and inside them thex
variable will already be of that type, so you can use it so.Testing it:
Output (try it on the Go Playground):
For a single type check you may also use type assertion:
There are also other ways, using package
reflect
you can write a more general (and slower) solution, but if you're just starting Go, you shouldn't dig into reflection yet.icza's answer is correct, but is not recommended by go creators:
A better approach may be to define a function for each type you have: