Crate try_transform_mut [] [src]

This crate provides special handling for reference primitive type.

We know that the value a reference pointers to is kept alive during the full lifetime of the reference.

Many times a mutable reference is consumed by some specific handling, but they didn't bother return the mutable reference back to the caller even if they didn't give meaningful results. At most time this is fine, since you can just recreate the reference by borrow again. However there is a problem when the reference comes from an argument.

This crate catches this pattern and provide it as a trait TryTransform, making it possible without any NLL support.

use try_transform_mut::TryTransform;
 
fn get_default<'r, K: Hash + Eq + Copy, V: Default>(
    map: &'r mut HashMap<K, V>,
    key: K,
) -> &'r mut V {
    match map.try_transform(|m| m.get_mut(&key)) {
        Ok(value) => {
            value
        }
        Err(map) => {
            map.insert(key, V::default());
            map.get_mut(&key).unwrap()
        }
    }
}

Traits

TryTransform

A trait providing try_transform method to reference primitive type.