gogo-map

How to return key's value of a map of type empty interface


I have taken a variable like var u = make(map[string]interface{}) which means that a key could hold a string/int or another map.

When I do the following it gives error cannot use v (type interface {}) as type string in return argument: need type assertion which looks obvious as the generic map have no idea what should it search. How can I resolve the issue? The code is given below(DO note that currently, the map is entirely empty)

var u = make(map[string]interface{})

// Get function retrieves the value of the given key. If failed, it returns error.
func Get(k string) (string, error) {
    v, found := u[k]
    println(reflect.Type(v))
    if found {
        v = u[k]
        return v, nil
    }
    return v, errors.New(-1)
}

Solution

  • v, found := u[k] here v is interface{} type

    But your function return type is (string, nil) where you are returning (v, nil) or (interface{}, nil).

    interface{} can not convert into string automatically, need type assertion.

    data, ok := v.(string)
    

    You can return interface{} also and the consumer can decide which type it will converted.