dictx

package
v0.4.3 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2025 License: BSD-3-Clause Imports: 2 Imported by: 8

README


This package provides utility functions for working with dictionaries (maps) in Go. It includes functionalities for cloning, key retrieval, existence checks, value retrieval, and more. This package is useful for managing nested maps in a convenient and type-safe manner.

Features:

  • Clone: Create a deep copy of a dictionary.
  • KeysN: Retrieve a sorted list of keys up to a specified level of nesting.
  • Keys: Retrieve a sorted list of all keys in a dictionary.
  • IsExist: Check if a key exists in a dictionary.
  • Get: Retrieve a value from the dictionary by key with a default fallback.
  • Fetch: Get a value from the dictionary with type assertion.
  • Set: Add or update a key-value pair in the dictionary.
  • Merge: Merge two dictionaries recursively.
  • Delete: Remove a key from the dictionary.

Documentation

Index

Examples

Constants

View Source
const Separator = "."

Key separator character used for nested keys

Variables

This section is empty.

Functions

func Delete

func Delete(d Dict, key string)

Delete removes a key from the dictionary if it exists. It supports nested keys using the separator.

Example
package main

import (
	"fmt"

	"github.com/exonlabs/go-utils/pkg/abc/dictx"
)

func main() {
	d := dictx.Dict{
		"a": dictx.Dict{
			"b": dictx.Dict{
				"c": "value",
			},
		},
	}

	// Delete a key
	dictx.Delete(d, "a.b.c")

	// Check if the key was deleted
	exists := dictx.IsExist(d, "a.b.c")
	fmt.Println(exists)

}
Output:

false

func Fetch

func Fetch[T any](d Dict, key string, defaultValue T) T

Fetch retrieves a value from the dictionary by key with type casting conversion. If the key is not found, the defaultValue is returned.

Example
package main

import (
	"fmt"

	"github.com/exonlabs/go-utils/pkg/abc/dictx"
)

func main() {
	d := dictx.Dict{
		"a": dictx.Dict{
			"b": dictx.Dict{
				"c": 42,
			},
		},
	}

	// Fetch value with correct type (int)
	val := dictx.Fetch(d, "a.b.c", 0)
	fmt.Println(val)

	// Fetch value that doesn't exist (should return default value)
	val = dictx.Fetch(d, "a.b.d", 0)
	fmt.Println(val)

}
Output:

42
0

func Get

func Get(d Dict, key string, defaultValue any) any

Get retrieves a value from the dictionary by key. If the key is not found, the defaultValue is returned.

Example
package main

import (
	"fmt"

	"github.com/exonlabs/go-utils/pkg/abc/dictx"
)

func main() {
	d := dictx.Dict{
		"a": dictx.Dict{
			"b": dictx.Dict{
				"c": "value",
			},
		},
	}

	// Get an existing key
	val := dictx.Get(d, "a.b.c", "default")
	fmt.Println(val)

	// Get a non-existing key, return default value
	val = dictx.Get(d, "a.b.x", "default")
	fmt.Println(val)

}
Output:

value
default

func GetFloat

func GetFloat(d Dict, key string, defaultValue float64) float64

GetFloat retrieves a float value from the dictionary by key. If the key is not found, the defaultValue is returned.

func GetInt

func GetInt(d Dict, key string, defaultValue int) int

GetInt retrieves an integer value from the dictionary by key. If the key is not found, the defaultValue is returned.

func GetString

func GetString(d Dict, key string, defaultValue any) string

GetString retrieves a value as string from the dictionary by key. If the key is not found, the defaultValue is returned.

func GetUint

func GetUint(d Dict, key string, defaultValue uint) uint

GetUint retrieves an unsigned integer value from the dictionary by key. If the key is not found, the defaultValue is returned.

func IsExist

func IsExist(d Dict, key string) bool

IsExist checks if a key exists in the dictionary. It supports nested keys using the separator. Returns true if the key exists, false otherwise.

Example
package main

import (
	"fmt"

	"github.com/exonlabs/go-utils/pkg/abc/dictx"
)

func main() {
	d := dictx.Dict{
		"a": dictx.Dict{
			"b": dictx.Dict{
				"c": "value",
			},
		},
	}

	// Check if keys exist
	fmt.Println(dictx.IsExist(d, "a.b.c")) // true
	fmt.Println(dictx.IsExist(d, "a.b.d")) // false
	fmt.Println(dictx.IsExist(d, "a.x"))   // false

}
Output:

true
false
false

func Keys

func Keys(d Dict) []string

Keys returns a list of all keys in the dictionary, regardless of nesting levels. It omits zero-length keys.

func KeysN

func KeysN(d Dict, n int) []string

KeysN returns a list of keys up to N levels nested. If n is 1, only top-level keys are returned. If n is greater than 1, it retrieves nested keys accordingly. Zero-length keys are omitted from the results.

Example
package main

import (
	"fmt"

	"github.com/exonlabs/go-utils/pkg/abc/dictx"
)

func main() {
	d := dictx.Dict{
		"a": dictx.Dict{
			"b": dictx.Dict{
				"c": dictx.Dict{
					"d": "value",
				},
			},
		},
	}

	// Retrieve all keys with unlimited depth
	keys := dictx.KeysN(d, -1)
	fmt.Println(keys)

	// Retrieve top-level keys only
	keysTopLevel := dictx.KeysN(d, 1)
	fmt.Println(keysTopLevel)

}
Output:

[a.b.c.d]
[a]

func Merge

func Merge(src, updt Dict)

Merge updates a source dictionary recursively with an update dictionary. It merges keys and values, allowing nested dictionaries to be updated as well.

Example
package main

import (
	"fmt"

	"github.com/exonlabs/go-utils/pkg/abc/dictx"
)

func main() {
	src := dictx.Dict{
		"a": dictx.Dict{
			"b": "old_value",
		},
	}
	updt := dictx.Dict{
		"a": dictx.Dict{
			"b": "new_value",
			"c": "new_key",
		},
	}

	// Merge the update dict into the source dict
	dictx.Merge(src, updt)

	// Print the updated source dictionary
	fmt.Println(src)

}
Output:

map[a:map[b:new_value c:new_key]]

func Set

func Set(d Dict, key string, newValue any)

Set adds a new value in the dictionary by key. If the key already exists, its value is overwritten.

Example
package main

import (
	"fmt"

	"github.com/exonlabs/go-utils/pkg/abc/dictx"
)

func main() {
	d := dictx.Dict{}

	// Set a nested value
	dictx.Set(d, "a.b.c.d", "new_value")

	// Get the value to confirm it was set correctly
	val := dictx.Get(d, "a.b.c.d", "default")
	fmt.Println(val)

}
Output:

new_value

func String

func String(d Dict) string

String returns string representation of keys and values.

Types

type Dict

type Dict = map[string]any

Dict type representation as a map with string keys and any values

func Clone

func Clone(d Dict) (Dict, error)

Clone creates a deep copy of a Dict. It returns a new dictionary that is a copy of the original, preserving the structure and values.

Example
package main

import (
	"fmt"

	"github.com/exonlabs/go-utils/pkg/abc/dictx"
)

func main() {
	d := dictx.Dict{
		"a": dictx.Dict{
			"b": "value",
		},
	}
	cloned, err := dictx.Clone(d)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	// Print original and cloned dictionary
	fmt.Println("Original:", d)
	fmt.Println("Cloned:", cloned)

}
Output:

Original: map[a:map[b:value]]
Cloned: map[a:map[b:value]]

Jump to

Keyboard shortcuts

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