From and Into are great

<
>
July 11, 2021

Rust’s From and Into traits are great.
Once you implemented one of them, they allow you to convert between two types simply by calling either Target::from(source) or source.into().
In previous posts you might have noticed the deeply nested constructions of Items such as:

fn offer(&mut self, _pos: &PosRelative) -> Option<Item> {
    self.product
        .take()
        .map(|x| Item::Material(Material::Plate(x)))
    }
}

This is caused due to the definition of the Item type:

pub enum Item {
    Material(Material),
    Structure(Structure),
    ...
}

pub enum Material {
    Ore(Ore),
    Plate(Plate),
    ...
}

pub enum Plate {
    Iron,
    Copper,
}

To e.g. construct an Item from a Plate one has to also mention the intermediate Material type.
This is quite annoying to type and reduces the readability of the code.
But once the From conversion is implemented:

impl From<Plate> for Item {
    fn from(x: Plate) -> Self {
        Self::Material(Material::Plate(x))
    }
}

The previously long construction can be simplified to a single .into() call:

fn offer(&mut self, _pos: &PosRelative) -> Option<Item> {
    self.product.take().map(|x| x.into())
}

Due to the many conversions within Factor Y from specific types such as Plate to more generic ones such as Material or even Item, using From or Into is incredibly helpful.