SyncMap
is a type-safe and generic interface around Go's sync.Map
. It simplifies the use of sync.Map
through allowing you to define the types on both keys and values.
It makes using sync.Map
more simple and more safe through letting you define the types on keys and values when you create the sync.Map
.
Using SyncMap
has these advantages:
- Generic Type: Helps avoid type mismatches during runtime.
- Clean Code: No need on type assertions from
interface{}
. - Simple Usage: Works just same as
sync.Map
, same methods.
go get github.com/yyle88/syncmap
Here's a simple example showing how you can use SyncMap
to store and retrieve structured data in a safe way.
package main
import (
"fmt"
"github.com/yyle88/syncmap"
)
type Student struct {
Name string
Age int
}
func main() {
// Create a SyncMap with string keys and Student values
studentMap := syncmap.NewMap[string, *Student]()
// Add a student to the map
studentMap.Store("s1", &Student{Name: "Alice", Age: 20})
// Retrieve the student
if student, ok := studentMap.Load("s1"); ok {
fmt.Printf("Student: Name: %s, Age: %d\n", student.Name, student.Age) // Output: Student: Name: Alice, Age: 20
}
}
⬆️ Source: Source
- Defines Type-Safe Keys and Values: The key is a
string
, and the value is aStudent
struct pointer, avoiding the use ofinterface{}
on values. - Simplifies Data Access: No need on type assertions like
student = v.(*Student)
when retrieving data. - Works Same with
sync.Map
: Functions likeStore
andLoad
are the same as insync.Map
, so you don't need to learn new methods.
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
})
}
⬆️ Source: Source
- Store and Delete: This example shows how to add multiple items and delete one using the
Delete
method. - Iterate Through Data: The
Range
method is used to iterate through the key-value pairs in the map, which simplifies traversing the map. - Simplified Operations: Just like with the previous example, no type assertions are needed, and the usage is straightforward.
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 item. |
Delete(key) |
Removes the item from the map. |
Range(func) |
Iterates through each item in the map. |
Has(key) |
Checks if a key exists in the map. |
Count() |
Returns the count of items in the map. |
Keys() |
Returns the keys from the map. |
Values() |
Returns the values from the map. |
Same as sync.Map
with extra functions.
LoadOrStore - Get existing or store new value:
value, loaded := m.LoadOrStore("key", "default")
if loaded {
// Value existed, returned existing value
} else {
// Value was stored, returned new value
}
Swap - Replace value and get previous:
previous, existed := m.Swap("key", "new-value")
if existed {
fmt.Println("Previous value:", previous)
}
CompareAndSwap - Update when value matches:
success := m.CompareAndSwap("key", "old-value", "new-value")
if success {
// Value was updated
}
CompareAndDelete - Delete when value matches:
deleted := m.CompareAndDelete("key", "expected-value")
if deleted {
// Item was deleted
}
Check existence:
if m.Has("key") {
// Key exists in map
}
Get count of items:
count := m.Count()
fmt.Println("Map has", count, "items")
Get the keys:
keys := m.Keys()
for _, k := range keys {
fmt.Println("Key:", k)
}
Get the values:
values := m.Values()
for _, v := range values {
fmt.Println("Value:", v)
}
MIT License. See LICENSE.
Contributions are welcome! Report bugs, suggest features, and contribute code:
- 🐛 Found a mistake? Open an issue on GitHub with reproduction steps
- 💡 Have a feature idea? Create an issue to discuss the suggestion
- 📖 Documentation confusing? Report it so we can improve
- 🚀 Need new features? Share the use cases to help us understand requirements
- ⚡ Performance issue? Help us optimize through reporting slow operations
- 🔧 Configuration problem? Ask questions about complex setups
- 📢 Follow project progress? Watch the repo to get new releases and features
- 🌟 Success stories? Share how this package improved the workflow
- 💬 Feedback? We welcome suggestions and comments
New code contributions, follow this process:
- Fork: Fork the repo on GitHub (using the webpage UI).
- Clone: Clone the forked project (
git clone https://github.com/yourname/repo-name.git
). - Navigate: Navigate to the cloned project (
cd repo-name
) - Branch: Create a feature branch (
git checkout -b feature/xxx
). - Code: Implement the changes with comprehensive tests
- Testing: (Golang project) Ensure tests pass (
go test ./...
) and follow Go code style conventions - Documentation: Update documentation to support client-facing changes and use significant commit messages
- Stage: Stage changes (
git add .
) - Commit: Commit changes (
git commit -m "Add feature xxx"
) ensuring backward compatible code - Push: Push to the branch (
git push origin feature/xxx
). - PR: Open a merge request on GitHub (on the GitHub webpage) with detailed description.
Please ensure tests pass and include relevant documentation updates.
Welcome to contribute to this project via submitting merge requests and reporting issues.
Project Support:
- ⭐ Give GitHub stars if this project helps you
- 🤝 Share with teammates and (golang) programming friends
- 📝 Write tech blogs about development tools and workflows - we provide content writing support
- 🌟 Join the ecosystem - committed to supporting open source and the (golang) development scene
Have Fun Coding with this package! 🎉🎉🎉