#default-value #consume #default #take

consumable

Consume the value by replacing it with the default value and returning the previous value

1 unstable release

0.1.0 Oct 29, 2024

#1324 in Rust patterns

MIT/Apache

3KB

Consume the value by replacing it with the default value and returning the previous value

use consumable::*;

let mut x : i32 = 42;
assert_eq!(x.consume(), 42);
assert_eq!(x, i32::default());
pub trait Consumable
{
    fn consume(&mut self) -> Self;
}

impl<T : Default> Consumable for T 
{
    fn consume(&mut self) -> Self { std::mem::take(self) }
}

lib.rs:

Consume the value by replacing it with the default value and returning the previous value

use consumable::*;

let mut x : i32 = 42;
assert_eq!(x.consume(), 42);
assert_eq!(x, i32::default());

No runtime deps