| Crates.io | shared-type |
| lib.rs | shared-type |
| version | 1.0.0 |
| created_at | 2025-01-29 21:04:34.702223+00 |
| updated_at | 2025-01-29 21:04:34.702223+00 |
| description | Shared type alias and several traits to simplify working with Arc |
| homepage | |
| repository | https://github.com/an-dr/shared-type-rs |
| max_upload_size | |
| id | 1535443 |
| size | 9,292 |
Shared type alias and several traits to simplify working with Arc<Mutex<T>>
| With the crate | Without the crate |
|---|---|
var.into_shared() |
Arc::new(Mutex::new(var)) |
let r = var.with_inner(|v|{...}) |
let r = var.lock().ok().map(|mut v| {...}); |
let r = var.try_with_inner(|v|{...}) |
let r = var.try_lock().ok().map(|mut v| {...}); |
The crate provides a shared type alias Shared<T> which is a shorthand for Arc<Mutex<T>>. It also provides following traits:
Shared<T> (Arc<Mutex<T>>)Shared<T>Add the following to your Cargo.toml:
shared-type = "1.0.0"
Code!
let vec = vec![1, 2, 3];
let vec_shared = vec.into_shared(); // Arc<Mutex<Vec<i32>>>
// The simple example of using the shared value that will wait for
// the lock to become available and then call the closure
vec_shared.with_inner(|vec| {
vec.push(4);
});
// The same example but with the return value
let new_len = vec_shared.with_inner(|vec| {
vec.push(5);
vec.len()
});
// Or we can use the `try_with` to non-blocking access
let newer_len = vec_shared.try_with_inner(|vec| {
vec.push(6);
vec.len()
});
Find the full example in the examples directory.