-2

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)
}
Volatil3
  • 11,721
  • 33
  • 112
  • 218

2 Answers2

2

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.

Volatil3
  • 11,721
  • 33
  • 112
  • 218
Eklavya
  • 15,459
  • 4
  • 14
  • 41
  • 1
    Ah. OK now I got it. Since the map could contain either string or anything, so it is better to return an `interface` and then the consumer of the function should figure out the type of return value whether it is a string, interface or otherwise and use accordingly? – Volatil3 Apr 16 '20 at 13:33
  • yes you can return interface{} also and consumer can decide which type it will converted – Eklavya Apr 16 '20 at 13:35
2

I'm not sure what's your question. But you're getting this error because you are trying to return interface{} as concrete type string. If you want to return string, and you're sure that value of map is always string(then why are you using map[string]interface{} instead of map[string]string?) you can get underlying type of interface by using type assertion:

s, ok := v.(string)
Grigoriy Mikhalkin
  • 3,500
  • 1
  • 12
  • 29
  • 1
    Now I got it. Since the map could contain either string or anything, so it is better to return an `interface` and then the consumer of the function should figure out the type of return value whether it is a string, interface or otherwise and use accordingly? – Volatil3 Apr 16 '20 at 13:33
  • 1
    @Volatil3 Yep, that would be good solution, to leave that to consumer – Grigoriy Mikhalkin Apr 16 '20 at 13:35