Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/zxch3n/arref
Getting mutable references from the same array safely in Rust
https://github.com/zxch3n/arref
Last synced: 2 months ago
JSON representation
Getting mutable references from the same array safely in Rust
- Host: GitHub
- URL: https://github.com/zxch3n/arref
- Owner: zxch3n
- License: mit
- Created: 2022-09-26T11:53:16.000Z (over 2 years ago)
- Default Branch: master
- Last Pushed: 2022-09-26T12:31:00.000Z (over 2 years ago)
- Last Synced: 2024-04-25T14:03:22.527Z (8 months ago)
- Language: Rust
- Homepage:
- Size: 3.91 KB
- Stars: 3
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
Getting mutable references to two elements from the same array safely is
cumbersome in Rust. This tiny lib provides method to make it easier.[array_mut_ref!] checks whether the user borrows the same element at runtime.
```rust
use arref::array_mut_ref;
let mut arr = vec![1, 2, 3, 4];
let (a, b) = array_mut_ref!(&mut arr, [1, 2]);
assert_eq!(*a, 2);
assert_eq!(*b, 3);
let (a, b, c) = array_mut_ref!(&mut arr, [1, 2, 0]);
assert_eq!(*c, 1);// ⚠️ The following code will panic. Because we borrow the same element twice.
// let (a, b) = array_mut_ref!(&mut arr, [1, 1]);
```Alternatively, you can use [mut_twice]. It won't panic if you borrow the same
element twice. It'll return an `Err(&mut T)` instead.```rust
use arref::mut_twice;
let mut arr = vec![1, 2, 3];
let (a, b) = mut_twice(&mut arr, 1, 2).unwrap();
assert_eq!(*a, 2);
assert_eq!(*b, 3);
let result = mut_twice(&mut arr, 1, 1);
assert!(result.is_err());
if let Err(v) = result {
assert_eq!(*v, 2);
}
```