Function borrowme::borrow_mut
source · pub fn borrow_mut<T>(value: &mut T) -> T::TargetMut<'_>
Expand description
Borrow mutably from the given value.
This helper function is provided so that you don’t have to have the
BorrowMut
trait in scope, and make it explicit when this crate is being
used since “borrowing” is not a cheap operation in this crate.
This also prevents conflicts with the built-in
BorrowMut
.
§Examples
#[borrowme]
struct Word<'a> {
text: &'a mut String,
}
impl OwnedWord {
fn new(text: &str) -> Self {
Self { text: text.to_owned() }
}
}
#[borrowme]
#[derive(Default)]
struct Dictionary<'a> {
#[borrowme(mut)]
words: Vec<Word<'a>>,
}
fn uppercase(dictionary: Dictionary<'_>) {
for word in dictionary.words {
*word.text = word.text.to_uppercase();
}
}
let mut dictionary = OwnedDictionary::default();
dictionary.words.push(OwnedWord::new("Hello"));
dictionary.words.push(OwnedWord::new("World"));
uppercase(borrowme::borrow_mut(&mut dictionary));
assert_eq!(dictionary.words[0].text, "HELLO");
assert_eq!(dictionary.words[1].text, "WORLD");