Question: Eat your cake and have it too!
Dajamante opened this issue · 3 comments
Dear Nathan,
Is it possible to change the From
impl
into an Into
implementation? (impl Into<Cake> for Party)
?
You said that From/Into were mirrors of each other.
Would that even make sense?
impl From<Party> for Cake {
fn from(party: Party) -> Self {
party.cake
}
}
smell_cake(party);
pub fn smell_cake<T: Into<Cake>>(something: T) {
println!("Hmm...something smells like a {:?} cake!", something.into());
}
If you implement:
From<Party> for Cake
then the standard library implements this for you automatically!
Into<Cake> for Party
If you would rather implement this ☝🏻 manually, you may. But implementing the Into
will not get you a free implementation of From
, so you'll have to implement them both manually if you want them both.
Does that answer your question?
Yes thank you it replies PartialEq
🙂.
Would it make sense to implement it the other way around (even with the extra into()
function) or is it very not idiomatic?
The idiomatic thing to do is to implement the From
trait, and then the Into
trait is implemented for you. It is usually more idiomatic to use the Into
trait when defining functions! Sort of weird, eh?