Documentation
¶
Overview ¶
Package fields provides types and functions to work with key-value pairs.
The package offers three primary abstractions:
- Field: A key-value pair where the key is a string and the value can be any type.
- Dict: A map-based collection of unique fields, providing efficient key-based lookup.
- List: An ordered collection of fields that preserves insertion order.
Fields can be created using the F constructor, and both Dict and List provide conversion methods between the two collection types. All types implement String() for consistent string representation.
Example usage:
// Create fields
f1 := fields.F("status", "success")
f2 := fields.F("code", 200)
// Working with a List (ordered collection)
var list fields.List
list.Add(f1, f2)
fmt.Println(list) // "(status=success, code=200)"
// Working with a Dict (unique key collection)
dict := fields.Dict{}
dict.Add(f1, f2, fields.F("status", "updated")) // overwrites "status"
fmt.Println(dict) // "(status=updated, code=200)" (order may vary)
// Converting between types
list2 := dict.ToList() // order unspecified
dict2 := list.ToDict() // last occurrence of each key wins
Index ¶
Constants ¶
const CollectionSep = ", "
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Dict ¶
Dict is a map-based collection of unique fields, keyed by string. It provides efficient lookup and overwrites duplicate keys.
func (Dict) Add ¶
Add inserts or updates fields in the Dict, overwriting existing keys if present.
Example:
d := fields.Dict{"foo": "bar"}
d.Add(fields.F("baz", 42), fields.F("foo", "qux")) // d["foo"] == "qux"
func (Dict) All ¶ added in v0.4.0
All returns an iterator over all key-value pairs in the Dict as iter.Seq2[string, any].
Example:
for k, v := range d.All() {
fmt.Println(k, v)
}
func (Dict) String ¶
String returns the Dict as a string in the format "(key1=val1, key2=val2)". Returns an empty string if the Dict is empty. The order of fields is unspecified.
type Field ¶
Field represents a key-value pair, where the key is a string and the value can be any type.
func F ¶
F creates a new Field with the given key and value.
Example:
f := fields.F("user", "alice")
type List ¶
type List []Field //nolint:recvcheck //we need Add to be a pointer receiver to modify original value.
List is an ordered collection of Field values, preserving insertion order. Such collection do not check for duplicate keys.
func (*List) Add ¶
Add one or more fields to the List, modifying it.
Example:
var l fields.List
l.Add(fields.F("foo", "bar"), fields.F("baz", 42))
func (List) All ¶ added in v0.4.0
All returns an iterator over all key-value pairs in the List as iter.Seq2[string, any].
Example:
for k, v := range l.All() {
fmt.Println(k, v)
}
func (List) String ¶
String returns the List as a string in the format "(key1=val1, key2=val2)". Returns an empty string if the List is empty.