
From and Into Traits in Rust and Implementing Both Correctly
Implement From and you get Into for free. Learn the conventions, how the question mark uses From, and when TryFrom is the right trait.
Everything you need to level up your coding skills.

Implement From and you get Into for free. Learn the conventions, how the question mark uses From, and when TryFrom is the right trait.

E0038 means a trait is not dyn compatible, so you cannot write dyn Trait for it. Learn the rules that break it and four ways to restore object safety.

Generic code compiles once per type, and that can bloat a binary and slow builds. Find the biggest instantiations with cargo llvm-lines and cut them with inner functions and dyn.

Model states as an enum when they change at run time and as types when the order is known at compile time. See both versions of a connection and which one to pick.

E0282 means the compiler cannot work out a type from context. Add a turbofish, a let annotation or a typed collect and it goes away.

E0308 mismatched types means the compiler expected one type and found another. Learn the five shapes it takes, from a missing semicolon to if branches that differ.

Test code that calls out to services with a hand-written fake or a Mockall mock. Compare setup cost, what each can assert and the cases where a fake is the better tool.

E0599 means no method with that name exists on that type, or the trait providing it is not in scope or not implemented. Find which of five causes applies.

E0277 means a type does not implement a trait that the code requires. Read the required-by note, then add a derive, an impl or a bound.

Depend on a trait that you own, not on a concrete client. Learn generics versus Arc dyn for wiring, when a trait is not worth it and how to keep it small.

Use an associated type when each implementor has exactly one answer and a generic parameter when a type can implement the trait many ways. The Iterator and From traits show both.

In argument position impl Trait is a generic, in return position it hides one concrete type, and dyn Trait is for several. Here is how to pick in each place.
We send one email when a new post is published. No spam.