
SyncMap - A Type-Safe Interface to sync.Map
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.
README
中文说明
Advantages of SyncMap
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.
Installation
go get github.com/yylego/syncmap
How to Use SyncMap
Here's a simple example showing how you can use SyncMap to store and retrieve structured data in a safe way.
Example 1: Storing and Retrieving Data
package main
import (
"fmt"
"github.com/yylego/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
Explanation
- Defines Type-Safe Keys and Values: The key is a
string, and the value is a Student struct pointer, avoiding the use of interface{} on values.
- Simplifies Data Access: No need on type assertions like
student = v.(*Student) when retrieving data.
- Works Same with
sync.Map: Functions like Store and Load are the same as in sync.Map, so you don't need to learn new methods.
Example 2: Storing, Deleting, and Iterating Through Data
package main
import (
"fmt"
"github.com/yylego/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
Explanation
- 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 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 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.
Examples
Atomic Operations
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)
}
Comparison Operations
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
}
Helper Functions
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)
}
📄 License
MIT License. See LICENSE.
🤝 Contributing
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
🔧 Development
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.
🌟 Support
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! 🎉🎉🎉
GitHub Stars
