How to convert interface{} to map

后端 未结 3 516
慢半拍i
慢半拍i 2021-01-31 08:43

I am trying to create a function that could accept following

*struct
[]*struct
map[string]*struct

Here struct could be any struct not just a sp

3条回答
  •  借酒劲吻你
    2021-01-31 09:25

    You don't need reflect here. Try:

    v, ok := in.(map[string]*Book)
    if !ok {
        // Can't assert, handle error.
    }
    for _, s := range v {
        fmt.Printf("Value: %v\n", s)
    }
    

    Same goes for the rest of your function. It looks like you're using reflection when you would be better served by a type switch.


    Alternatively, if you insist on using reflection here (which doesn't make a lot of sense) you can also use Value.MapKeys with the result from your ValueOf (see the answer https://stackoverflow.com/a/38186057/714501)

提交回复
热议问题