lookup

package
v1.76.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 15, 2025 License: MIT, MIT Imports: 4 Imported by: 0

README

type Cast struct {
  Actor, Role string
}

type Serie struct {
  Cast []Cast
}

series := map[string]Serie{
  "A-Team": {Cast: []Cast{
    {Actor: "George Peppard", Role: "Hannibal"},
    {Actor: "Dwight Schultz", Role: "Murdock"},
    {Actor: "Mr. T", Role: "Baracus"},
    {Actor: "Dirk Benedict", Role: "Faceman"},
  }},
}

value, _ := lookup.DotP(series, "A-Team.Cast.0.Actor")
fmt.Println(q, "->", value.Interface())

Documentation

Overview

Small library on top of reflect for make lookups to Structs or Maps. Using a very simple DSL you can access to any property, key or value of any value of Go.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidIndexUsage = errors.New("invalid index usage")
	ErrKeyNotFound       = errors.New("not found")
	ErrIndexOutOfBounds  = errors.New("index out of bounds")
)

Functions

func DotP

func DotP(i interface{}, path string) (reflect.Value, error)

DotP performs a lookup into a value, using a string. Same as `Lookup` but using a string with the keys separated by `.`

Example
type Cast struct {
	Actor, Role string
}

type Serie struct {
	Cast []Cast
}

series := map[string]Serie{
	"A-Team": {Cast: []Cast{
		{Actor: "George Peppard", Role: "Hannibal"},
		{Actor: "Dwight Schultz", Role: "Murdock"},
		{Actor: "Mr. T", Role: "Baracus"},
		{Actor: "Dirk Benedict", Role: "Faceman"},
	}},
}

q := "A-Team.Cast.0.Actor"
value, _ := DotP(series, q)
fmt.Println(q, "->", value.Interface())
Output:

A-Team.Cast.0.Actor -> George Peppard

func P

func P(i interface{}, path ...string) (reflect.Value, error)

P performs a lookup into a value, using a path of keys. The key should match with a Field or a MapIndex. For slice you can use the syntax key[index] to access a specific index. If one key owns to a slice and an index is not specificied the rest of the path will be apllied to evaley value of the slice, and the value will be merged into a slice.

Example
type ExampleStruct struct {
	Values struct {
		Foo int
	}
}

i := ExampleStruct{}
i.Values.Foo = 10

value, _ := P(i, "Values", "Foo")
fmt.Println(value.Interface())
Output:

10

Types

type MyKey

type MyKey string

type MyStruct

type MyStruct struct {
	String      string
	Map         map[string]int
	Nested      *MyStruct
	StructSlice []*MyStruct
	Interface   interface{}
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL