Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check Type of Variable in Go

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading