Quick and Dirty Object Access in Go

27 March 2026

Updated: 27 March 2026

Assumed audience: Developers/technical people who use Go as a programming language

This probably isn’t too difficult to write but it’s recursive and I had fun putting it together so here it is

Basically, I was trying to access a deeply nested object that was parsed from BurntSushi/toml in some generic fashion and it was getting annoying to constantly cast things and do the necessary checks at every level so I made two utilities that can access nested data a bit more conveniently

First off, here’s a helper type to sprinkle around:

1
type dynamic = map[string]any

Then, here’s the version that will panic if it hits something it’s not expecting:

1
func unsafeIndex(data dynamic, path ...string) any {
2
if len(path) == 0 {
3
return data
4
}
5
6
inner := data[path[0]]
7
if len(path) == 1 {
8
return inner
9
}
10
11
return unsafeIndex(inner.(dynamic), path[1:]...)
12
}

And the version that returns the appropriate errors along the way:

1
func safeIndex(data dynamic, path ...string) (any, error) {
2
if len(path) == 0 {
3
return data, nil
4
}
5
6
inner, ok := data[path[0]]
7
if !ok {
8
return data, fmt.Errorf("Error indexing path %v for %v", path, data)
9
}
10
11
if len(path) == 1 {
12
return inner, nil
13
}
14
15
dyn, ok := inner.(dynamic)
16
if !ok {
17
return dyn, fmt.Errorf("Error indexing into inner struct %v for %v", path, inner)
18
}
19
20
return safeIndex(dyn, path[1:]...)
21
}

Using them is also fairly normal, as seen below:

1
// whatever you're doing to decode the data. e.g. JSON/TOML parser
2
var output dynamic
3
decodeData(FILE_CONTENT, &output)
4
5
dynamicSources, err := safeIndex(output, "some", "deeply", "nested", "property")
6
if err != nil {
7
panic(err)
8
}