pub trait SetVariant<T, Marker = ()> {
    fn set_variant(&mut self, value: T);
}
Expand description

This trait is for setting an inner value with the correct associated type to the given value

set_variant looks at the type of the parameter value and if one of the fields has this type, the enums active field is changed to this field with inner value set to given parameter.

This method is guaranteed to succeed in the sense that if a value is given whose type does not match the type of any field, the program will not compile.

Example:

use variant_access_traits::*;
use variant_access_derive::*;

#[derive(VariantAccess)]
enum Enum {
    F1(i64),
    F2(bool)
}
let mut instance = Enum::F1(42);

instance.set_variant(false); // instance now is equal to Enum::F2(false)
// instance.set_variant(""); will not compile as Enum has no field of type &str

This method uses type inference to try and determine which field to use. However this can be ambiguous sometimes.

Example:

use variant_access_traits::*;
use variant_access_derive::*;

#[derive(VariantAccess)]
enum Enum {
    F1(i32),
    F2(i64)
}

let mut instance = Enum::F1(42);
instance.set_variant(1); // Is instance equal to Enum::F1(1) or Enum::F2(1) ???

// Do this instead
instance.set_variant(1_i32); // instance equals Enum::F1(1)
instance.set_variant(1_i64); // instance equal Enum::F2(1)

This trait has a generic paramer 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.

Required Methods

Implementors