mapper

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2026 License: MIT Imports: 1 Imported by: 0

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

View Source
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.

Example (SetSharesState)

Set chains, but the value it returns shares the backing map with the receiver - it is not a copy, so a write through one is visible through both.

package main

import (
	"fmt"

	"github.com/diegodesousas/go-devkit/pkg/mapper"
)

// 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() {
	first := mapper.New[Currency, float64]()
	second := first.Set("BRL", 1)

	second.Set("USD", 5.4)

	rate, err := first.Get("USD")
	fmt.Println(rate, err)

}
Output:
5.4 <nil>

func New

func New[K ~string, T any]() Mapper[K, T]

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

Jump to

Keyboard shortcuts

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