9

I want to check the output variable is map[string]string or not. the output should be a map[string]string and it should be a ptr.

I checked ptr value. But I don't know how to check the key of map if is string or not.

sorry for my bad english

import (
    "fmt"
    "reflect"
)

func Decode(filename string, output interface{}) error {
    rv := reflect.ValueOf(output)
    if rv.Kind() != reflect.Ptr {
        return fmt.Errorf("Output should be a pointer of a map")
    }
    if rv.IsNil() {
        return fmt.Errorf("Output in NIL")
    }
    fmt.Println(reflect.TypeOf(output).Kind())
    return nil
}
ahmdrz
  • 365
  • 2
  • 6
  • 14
  • 1
    Using [type switch](https://golang.org/ref/spec#Type_switches) or [type assertion](https://golang.org/ref/spec#Type_assertions). See this possible duplicate question+answer: [How to check if interface{} is a slice](http://stackoverflow.com/questions/40343471/how-to-check-if-interface-is-a-slice) – icza Nov 02 '16 at 16:29
  • sure. So I know its a map ! how to check its map[string]string or map[string]int and etc... – ahmdrz Nov 07 '16 at 08:45

1 Answers1

26

You don't have to use reflect at all for this. A simple type assert will suffice;

unboxed, ok := output.(*map[string]string)
if !ok {
    return fmt.Errorf("Output should be a pointer of a map")
}
if unboxed == nil {
    return fmt.Errorf("Output in NIL")
}
// if I get here unboxed is a *map[string]string and is not nil
evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115