GetOrInsert

Trait GetOrInsert 

Source
pub trait GetOrInsert<T> {
    // Required methods
    fn insert(&mut self, value: T) -> &mut T;
    fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T;

    // Provided methods
    fn get_or_insert(&mut self, value: T) -> &mut T { ... }
    fn get_or_insert_default(&mut self) -> &mut T
       where T: Default { ... }
}
Expand description

A trait for enum types that support .insert(x) method which sets the enum variant to something unique for x and returns a mutable reference to the value.

The most trivial example is Option<T>.

This operation is somehow not trivial to write in Rust (See the following sample generated code). #[derive(GetOrInsert)] macro provides an implementation for enums with every variant having a single distinct field types (or an unit type like Option::None).

§Example

If you write an enum like this:

use ::derive_insert::GetOrInsert;
#[derive(GetOrInsert)]
pub enum Foo {
   Bar(i32),
   Baz(String),
   AnEmptyVariant,
}

The following code will be generated:

impl GetOrInsert<i32> for Foo {
    fn insert(&mut self, value: i32) -> &mut i32 {
        *self = Self::Bar(value);
        match self {
            Self::Bar(ref mut x) => x,
            _ => unreachable!(),
        }
    }
    fn get_or_insert_with<F: FnOnce() -> i32>(&mut self, f: F) -> &mut i32 {
        match self {
            Self::Bar(ref mut x) => x,
            _ => self.insert(f()),
        }
    }
}
impl GetOrInsert<String> for Foo {
    // ... Same for Foo::Baz
}
// Foo::AnEmptyVariant is skipped because it's an unit variant

§Limitations

Currently, this derive macro only supports the enum variants which are:

  • tuple-like, single field (e.g. Option::Some(T)),
  • or unit variants (e.g. Option::None).

Required Methods§

Source

fn insert(&mut self, value: T) -> &mut T

Source

fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T

Provided Methods§

Source

fn get_or_insert(&mut self, value: T) -> &mut T

Source

fn get_or_insert_default(&mut self) -> &mut T
where T: Default,

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl<T> GetOrInsert<T> for Option<T>

Provides a default implementation for Option<T>.

Source§

fn insert(&mut self, value: T) -> &mut T

Source§

fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T

Implementors§