loopsdictionarygoslice

Using reflection in Go, how to iterate a known slice


With

    m := map[string]any{"a": 1, "b": 2, "c": []int{2, 3, 4}}
    v := reflect.ValueOf(m)

How to iterate through "c" in v?

See https://go.dev/play/p/KQ_UNjm-Vqd

package main

import (
    "fmt"
    "reflect"
)

func main() {
    m := map[string]any{"a": 1, "b": 2, "c": []int{2, 3, 4}}
    v := reflect.ValueOf(m)

    // Access the "c" key
    cKey := reflect.ValueOf("c")
    cValue := v.MapIndex(cKey)

    if cValue.IsValid() && cValue.Kind() == reflect.Slice {
        fmt.Println("Iterating through 'c':")
        for i := 0; i < cValue.Len(); i++ {
            fmt.Println(cValue.Index(i).Interface())
        }
    } else {
        fmt.Println("'c' is not a valid slice or key does not exist.")
    }

    if !cValue.IsValid() {
        fmt.Println("Key 'c' not found in the map")
        return
    }
    if cValue.Kind() != reflect.Slice {
        fmt.Println("Value for key 'c' is not a slice")
        return
    }
}

Solution

  • (I spent way too long in this)

    package main
    
    import (
    "fmt"
    "reflect"
    )
    
    func main() {
    m := map[string]any{"a": 1, "b": 2, "c": []int{2, 3, 4}}
    v := reflect.ValueOf(m)
    
    // Access the "c" key
    cKey := reflect.ValueOf("c")
    cValue := v.MapIndex(cKey)
    
    if !cValue.IsValid() {
        fmt.Println("Key 'c' not found in the map. ")
        return
    }
    
    // If the value is an interface, unwrap it
    if cValue.Kind() == reflect.Interface {
        cValue = cValue.Elem()
    }
    
    if cValue.Kind() != reflect.Slice {
        fmt.Println("Value for key 'c' is not a slice. ")
        return
    }
    
    fmt.Println("Iterating... ")
    for i := 0; i < cValue.Len(); i++ {
        fmt.Printf("Element %d: %v\n", i, cValue.Index(i).Interface())
    }
    }