[][src]Trait photonix::focus::Modify

pub trait Modify<Value> {
    fn modify(self, f: impl FnOnce(Value) -> Value) -> Self;
}

Updates the field of a container (struct/enum) by applying the provided function on the target value. Consumes the original container (unless it implements Copy), returns the updated one.

Auto-derive creates the implementation for all fields in structs and enum variants, works for structs and enums (both with named and unnamed fields) if

  • all fields have concrete types,
  • all field types are different.

If you are using the derive macro, and the actual enum variant happens to be different from the target variant, it returns the original version (see example).

Examples

 #[derive(Modify)]
 pub struct Person {
     pub name: String,
     pub age: u8,
 }

 let joe = Person { name: String::from("Joe"), age: 42 };
 let joe_older = joe.modify(|n: u8| n + 1); // help the compiler by specifying the field type

 assert_eq!(43, joe_older.age);

 let joel = joe_older.modify(|name: String| name + "l");

 assert_eq!("Joel", joel.name.as_str());

 #[derive(Debug, Modify, PartialEq)]
 pub enum Deviation {
     Signed(i32),
     Unsigned(u32),
 }

 let d = Deviation::Signed(-10);
 let d2 = Deviation::Unsigned(10);

 let d_neg = d.modify(|n: i32| -n);

 assert_eq!(Deviation::Signed(10), d_neg);

 let d2_neg = d2.modify(|n: i32| -n);

 assert_eq!(Deviation::Unsigned(10), d2_neg);

Required methods

fn modify(self, f: impl FnOnce(Value) -> Value) -> Self

Loading content...

Implementations on Foreign Types

impl<T> Modify<T> for Option<T>[src]

Loading content...

Implementors

Loading content...