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

How to check if var is map, slice or interface?

Does any one know if in Go I we have something like is ?

I need to understand if a var. is map or interface.

In Python I can do smt like this:

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

map = list()
print(map is list())
if map is list():
   # do something

In Go I tried to do the same:

var name map[string]string{
    "name": "surname"
}

var surname []interface{}

fmt.Println(reflect.TypeOf(name) map[string]string{})
fmt.Println(reflect.TypeOf(surname) []interface{})
if name == map[string]string{}{
    //do something
}

Thanks in advance!

>Solution :

Use a type assertion to assert that an interface value contains a concrete value of a type:

var v interface{} = /* some value */
if v, ok := v.(map[string]string); ok{
    // v has type map[string]string
}

Use a type switch when checking several types:

switch v := v.(type) {
case string:
     // v has type string
case map[string]string:
     // v has type map[string]string
default:
     panic(fmt.Sprintf("type %T not handled", v))
}
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