Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get values of a map interface with reflect in Go?

Tags:

go

I'm struggling to get the value of an interface map in Go.

val := reflect.ValueOf(Schema)
fmt.Println("VALUE = ", val)
fmt.Println("KIND = ", val.Kind())
if val.Kind() == reflect.Map {
    fmt.Println("len = ", val.Len())
    for key, element := range val.MapKeys() {
        fmt.Println(key, element) // how to get the value?
    }
}

This outputs:

VALUE =  map[testString:foobar testInt:1 testBoolean:true testNumber:1 testDateTime:2017-10-06 08:15:30 +0100 +0100]
KIND =  map
len =  5
0 testString
1 testInt
2 testBoolean
3 testNumber
4 testDateTime

My question:
How can I get the type and value of the map items?

like image 997
Bob van Luijt Avatar asked Jul 03 '18 18:07

Bob van Luijt


People also ask

What is reflect value Golang?

The reflect. ValueOf() Function in Golang is used to get the new Value initialized to the concrete value stored in the interface i. To access this function, one needs to imports the reflect package in the program.

How does reflect work Golang?

Reflection acts on three important reflection properties that every Golang object has: Type, Kind, and Value. 'Kind' can be one of struct, int, string, slice, map, or one of the other Golang primitives. The reflect package also allows you to modify the value of a specific field given the reflected value of a field.

Should I use reflection in Golang?

In those situations, you need to use reflection. Reflection gives you the ability to examine types at runtime. It also allows you to examine, modify, and create variables, functions, and structs at runtime. Reflection in Go is built around three concepts: Types, Kinds, and Values.


1 Answers

You were close, you can use the key returned form MapKeys and then use MapIndex to get the value of the map key. Below I use a switch statement to convert the value of the interface to the correct type.

package main

import (
    "fmt"
    "reflect"
)

func main() {
    Schema := map[string]interface{}{}
    Schema["int"] = 10
    Schema["string"] = "this is a string"
    Schema["bool"] = false

    val := reflect.ValueOf(Schema)
    fmt.Println("VALUE = ", val)
    fmt.Println("KIND = ", val.Kind())

    if val.Kind() == reflect.Map {
        for _, e := range val.MapKeys() {
            v := val.MapIndex(e)
            switch t := v.Interface().(type) {
            case int:
                fmt.Println(e, t)
            case string:
                fmt.Println(e, t)
            case bool:
                fmt.Println(e, t)
            default:
                fmt.Println("not found")

            }
        }
    }
}

Program Output:

VALUE =  map[int:10 string:this is a string bool:false]
KIND =  map
int 10
string this is a string
bool false
like image 158
jmaloney Avatar answered Sep 20 '22 18:09

jmaloney