Drill
This is a simple library to access the values of possibly nested struct
s with the well
known dotted notation from JSON.
Design
Take for example the following nested structures:
type Container struct {
A TypeA `json:"a"`
}
type TypeA struct {
B TypeB `json:"b"`
}
type TypeB struct {
C string `json:"c"`
}
The above might also have been references, maps (with string
keys), arrays or slices.
Take a look at the tests for more cases.
This library exposes a function to access the nested fields in dotted notation (for
example "a.b.c"
): Get
. It accepts interface{}
and returns a tuple (interface{}, error)
, so it is the caller's responsibility to check for errors and to cast the result
in the appropriate type. If, at whichever level, one of the keys in the chain is
missing, the Get
returns ErrKeyNotFound
.
From the example above
test := Container{A: A{B: B{C: "hi!"}}}
ret, err := Get(test, "a.b.c") // the error is nil
value := ret.(string) // this is "hi!"
ret, err := Get(test, "a.d") // this returns a nil interface and ErrKeyNotFound
This version is compatible with go<1.18. There is also a generics-based implementation
tagged as v2
.
Licence
This library is released in public domain. See LICENSE.