Documentation
¶
Overview ¶
Package mapper is a small generic registry keyed by a string-like type.
It exists to look values up by a named key type rather than a bare string, so the compiler rejects a lookup with the wrong kind of key:
type Currency string
rates := mapper.New[Currency, float64]()
rates.Set("BRL", 1).Set("USD", 5.4)
rate, err := rates.Get("BRL")
A key that was never set yields ErrValueNotFound.
Set chains, but it does not copy: the returned Mapper shares the backing map with the receiver, so both see every write. Treat the return value as a convenience for chaining, not as a new value.
A Mapper is not safe for concurrent use. Populate it during start-up and read it afterwards, or guard it yourself.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrValueNotFound = errors.New("err value not found")
ErrValueNotFound is returned by Get when the key was never set.
Functions ¶
This section is empty.
Types ¶
type Mapper ¶
type Mapper[K ~string, T any] interface { Set(key K, value T) Mapper[K, T] Get(k K) (value T, err error) }
Mapper is a registry of values of type T keyed by K, where K is any type whose underlying type is string.
Set returns the Mapper so calls can be chained, but the returned value shares the backing map with the receiver - it is not a copy. A Mapper is not safe for concurrent use.
func New ¶
New returns an empty Mapper.
Example ¶
package main
import (
"fmt"
"github.com/diegodesousas/go-devkit/pkg/mapper"
"github.com/pkg/errors"
)
// Currency is a named string type, which is what Mapper keys on. The compiler
// then rejects a lookup with a plain string from some other domain.
type Currency string
func main() {
rates := mapper.New[Currency, float64]()
rates.Set("BRL", 1).Set("USD", 5.4)
rate, err := rates.Get("USD")
if err != nil {
panic(err)
}
fmt.Println("USD:", rate)
_, err = rates.Get("JPY")
fmt.Println("JPY:", errors.Is(err, mapper.ErrValueNotFound))
}
Output: USD: 5.4 JPY: true