Trait variant_access_traits::GetVariant
source · [−]pub trait GetVariant<T, Marker = ()> {
fn get_variant(self) -> Result<T, VariantAccessError>;
fn get_variant_ref(&self) -> Result<&T, VariantAccessError>;
fn get_variant_mut(&mut self) -> Result<&mut T, VariantAccessError>;
}
Expand description
This trait is for extracting a reference to the raw values in an enum
get_variant returns a reference to the raw value of
the active field if it has the same type as the specified type.
Otherwise, an Err should be returned. It is intended to use
this function in conjunction with [has_variant
] / [contains_variant
]
to know that safe unwrapping can occur.
get_variant_mut is similar except it is for returning a mutable reference to the raw value of the active field.
Example:
use variant_access_traits::*;
use variant_access_derive::*;
#[derive(VariantAccess)]
enum Enum {
F1(i64),
F2(bool)
}
let instance = Enum::f1(42);
let inner: &i64 = instance.get_variant().unwrap(); // assigns &42 to inner_value
// let inner: &bool = instance.get_variant().unwrap() // panics because of unhandled Err.
// let inner: &i32 = instance.get_variant().unwrap() // will not compile as GetVariant<i32> is not implemented for Enum.
Works similarly for get_variant_mut if instance is mutable; returns mutable references instead.
This trait has a generic parameter Marker
for adding marker
structs. This is used if implementing this trait for enums with
more than one generic parameter in order to avoid definition clashes.