Created
May 27, 2024 11:47
-
-
Save shakahl/792f0ee27e368bab86f1371b26b6d3a7 to your computer and use it in GitHub Desktop.
Golang - Accessing a deep nested value from a map in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"fmt" | |
) | |
func GetNestedValue(m map[string]any, keys ...string) (any, error) { | |
if len(keys) == 0 { | |
return nil, errors.New("no keys provided") | |
} | |
var value any = m | |
for _, key := range keys { | |
switch v := value.(type) { | |
case map[string]any: | |
value = v[key] | |
default: | |
return nil, errors.New("key path not found") | |
} | |
} | |
return value, nil | |
} | |
func main() { | |
// Example nested map | |
nestedMap := map[string]any{ | |
"level1": map[string]any{ | |
"level2": map[string]any{ | |
"level3": "target_value", | |
}, | |
}, | |
} | |
value, err := GetNestedValue(nestedMap, "level1", "level2", "level3") | |
if err != nil { | |
fmt.Println("Error:", err) | |
} else { | |
fmt.Println("Value:", value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment