syncmap

package module
v1.0.16 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2025 License: MIT Imports: 2 Imported by: 2

README

GitHub Workflow Status (branch) GoDoc Coverage Status Supported Go Versions GitHub Release Go Report Card

SyncMap - A Type-Safe Wrapper for sync.Map

SyncMap is a type-safe and generic wrapper around Go's sync.Map. It simplifies the use of sync.Map by allowing you to define the types for both keys and values.

It makes using sync.Map easier and safer by letting you define the types for keys and values when you create the sync.Map.

README

中文说明

Why Choose SyncMap?

Using SyncMap has several advantages:

  • Generic Type: Helps avoid type mismatches during runtime.
  • Clearer Code: No need for type assertions from interface{}.
  • Simple Usage: Works just same as sync.Map, same methods.

Installation

go get github.com/yyle88/syncmap

How to Use SyncMap

Here’s a simple example showing how you can use SyncMap to safely store and retrieve structured data.

Example 1: Storing and Retrieving Data
package main

import (
	"fmt"
	"github.com/yyle88/syncmap"
)

type User struct {
	Name string
	Age  int
}

func main() {
	// Create a SyncMap with string keys and User values
	users := syncmap.NewMap[string, *User]()

	// Add a user to the map
	users.Store("u1", &User{Name: "Alice", Age: 30})

	// Retrieve the user
	if user, ok := users.Load("u1"); ok {
		fmt.Printf("User: Name: %s, Age: %d\n", user.Name, user.Age) // Output: User: Name: Alice, Age: 30
	}
}
Explanation
  1. Defines Clear Types: The key is a string, and the value is a User struct pointer, avoiding the use of interface{} for values.
  2. Simplifies Data Access: No need for manual type assertions like user = v.(*User) when retrieving data.
  3. Works Same with sync.Map: Functions like Store and Load are exactly the same as in sync.Map, so you don't need to learn new methods.
Example 2: Storing, Deleting, and Iterating Over Data
package main

import (
	"fmt"
	"github.com/yyle88/syncmap"
)

type Person struct {
	Name     string
	Age      int
	HomePage string
}

func main() {
	// Create a SyncMap with int keys and *Person values
	mp := syncmap.NewMap[int, *Person]()

	// Add some persons to the map
	mp.Store(1, &Person{
		Name:     "Kratos",
		HomePage: "https://go-kratos.dev/",
	})
	mp.Store(2, &Person{
		Name: "YangYiLe",
		Age:  18,
	})
	mp.Store(3, &Person{
		Name: "DiLiReBa",
		Age:  18,
	})

	// Delete the entry with key 3
	mp.Delete(3)

	// Iterate over all items in the map
	mp.Range(func(key int, value *Person) bool {
		fmt.Println(key, value.Name, value.Age, value.HomePage)
		return true
	})
}
Explanation
  1. Store and Delete: This example shows how to add multiple entries and delete one using the Delete method.
  2. Iterate Over Data: The Range method is used to iterate over all the key-value pairs in the map, which simplifies traversing the map compared to manually managing sync.Map's iteration.
  3. Simplified Operations: Just like with the previous example, no type assertions are required, and the usage is straightforward.

SyncMap API

SyncMap provides the following functions:

Function Description
Store(key, value) Adds or updates a key-value.
Load(key) Retrieves the value.
LoadOrStore(key, value) Returns the value if it exists; otherwise, adds a new key-value.
Delete(key) Removes the key-value pair from the map.
Range(func) Iterates over all key-value pairs in the map.

Same as sync.Map.


License

This project is open-source under the MIT License. You can find the full text of the license in the LICENSE file.


Contributing

We welcome contributions of all kinds! Whether it’s reporting a bug, suggesting a feature, or submitting code improvements.


Thank You

If you find this package valuable, give me some stars on GitHub! Thank you!!!


GitHub Stars

starring

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Map

type Map[K comparable, V any] struct {
	// contains filtered or unexported fields
}

Map is a generic wrapper for sync.Map that supports type-safe operations. Map 是一个面向 sync.Map 的泛型封装,支持精确的类型操作。

func New added in v1.0.16

func New[K comparable, V any]() *Map[K, V]

New creates a new instance of Map. New 创建一个新的 Map 实例。

func NewMap

func NewMap[K comparable, V any]() *Map[K, V]

NewMap creates a new instance of Map. NewMap 创建一个新的 Map 实例。

func (*Map[K, V]) CompareAndDelete

func (m *Map[K, V]) CompareAndDelete(key K, value V) bool

CompareAndDelete compares the existing value with the provided value and deletes the entry if they match. CompareAndDelete 比较存在的值与提供的值,如果匹配,则删除条目。

func (*Map[K, V]) CompareAndSwap

func (m *Map[K, V]) CompareAndSwap(key K, old, new V) bool

CompareAndSwap compares the existing value with the old value and swaps it with the new value if they match. CompareAndSwap 将存在的值与旧值比较,如果匹配,则替换为新值。

func (*Map[K, V]) Count

func (m *Map[K, V]) Count() (size int)

Count returns the count num of key-value pairs in the Map. Count 返回 Map 中的键值对数量。

func (*Map[K, V]) Debug

func (m *Map[K, V]) Debug()

Debug prints all key-value pairs for debugging purposes. Debug 打印所有键值对,主要用于调试逻辑。

func (*Map[K, V]) Delete

func (m *Map[K, V]) Delete(key K)

Delete removes the value associated with the specified key. Delete 删除指定键相关的值。

func (*Map[K, V]) GetMap

func (m *Map[K, V]) GetMap() map[K]V

GetMap returns all key-value pairs as a standard Go map. GetMap 返回所有键值对,格式为标准的 Go map。

func (*Map[K, V]) Keys

func (m *Map[K, V]) Keys() (keys []K)

Keys retrieves all keys from the Map. Keys 返回 Map 中的所有键。

func (*Map[K, V]) Load

func (m *Map[K, V]) Load(key K) (res V, ok bool)

Load retrieves the value associated with the specified key. Load 获取与指定键相关的值。

func (*Map[K, V]) LoadAndDelete

func (m *Map[K, V]) LoadAndDelete(key K) (res V, ok bool)

LoadAndDelete retrieves and removes the value associated with the specified key. LoadAndDelete 获取并删除与指定键相关的值。

func (*Map[K, V]) LoadOrStore

func (m *Map[K, V]) LoadOrStore(key K, new V) (V, bool)

LoadOrStore retrieves the value associated with the key or stores and returns the new value if the key does not exist. LoadOrStore 获取指定键相关的值,如果键不存在,则存储并返回新值。

func (*Map[K, V]) Range

func (m *Map[K, V]) Range(run func(key K, value V) bool)

Range iterates over all key-value pairs in the map. Range 遍历地图中的所有键值对。

func (*Map[K, V]) SetMap

func (m *Map[K, V]) SetMap(mp map[K]V)

SetMap adds or updates key-value pairs from a standard Go map. SetMap 将标准 Go map 中的键值对添加或更新到 Map。

func (*Map[K, V]) SetSyncMap

func (m *Map[K, V]) SetSyncMap(mp *Map[K, V])

SetSyncMap copies all key-value pairs from a Map. SetSyncMap 复制一个 Map 中的所有键值对到当前 Map。

func (*Map[K, V]) SetSyncMaps

func (m *Map[K, V]) SetSyncMaps(mps ...*Map[K, V])

SetSyncMaps copies all key-value pairs from multiple Maps. SetSyncMaps 将多个 Map 中的键值对复制到当前 Map。

func (*Map[K, V]) Store

func (m *Map[K, V]) Store(key K, value V)

Store sets the value for the specified key. Store 为指定的键设置值。

func (*Map[K, V]) Swap

func (m *Map[K, V]) Swap(key K, value V) (pre V, ok bool)

Swap replaces the value for the specified key and returns the previous value if it existed. Swap 替换指定键相关的值,并返回之前的值(如果存在)。

func (*Map[K, V]) Values

func (m *Map[K, V]) Values() (values []V)

Values retrieves all values from the Map. Values 返回 Map 中的所有值。

Jump to

Keyboard shortcuts

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