In other languages, I can check the type of a variable at run time like so:
# Python
return foo is str # check that variable foo is of type string, true or false
// C#
return foo.GetType() == typeof(string); // same
But, I can’t seem to find a similar construct in Go. This question asks what I’m interested, but the answer provides a switch statement format. While I could make my code work like that, it seems like a waste if all I’m interested is comparing a variable to a single type. I’d like a single expression which returns a boolean evaluating if a variable is of a given type.
>Solution :
What you need is a type assertion:
func f(v interface{}) {
s, ok:=v.(string)
if ok {
// v is a string, and s is that string
}
}
Or:
if s, ok:=v.(string); ok {
// Use s
}