skip to content

Why do Rust's guidelines say to implement `From` rather than `Into`, yet to write generic bounds as `T: Into<U>`?

level: middleimportance: must knowfreq 60%

answer

  1. the blanket impl runs one way
  2. an Into impl yields no From
  3. bounds: accept the widest set
  4. orphan rules before 1.41

basics

~20 s

Implementing From gives Into for free through core's blanket impl, while implementing Into gives no From. Bounds use Into for the reverse reason: T: Into<U> accepts every From-based conversion plus any type that only implements Into.

solid answer

~40 s

Core has `impl<T, U> Into<U> for T where U: From<T>` and no impl in the other direction. Implement `From<Feet> for Meters` and callers get both `Meters::from(f)` and `f.into()`; implement only `Into<Meters> for Feet` and `Meters::from(f)` does not exist (rustc reports E0308, because in that example the only `From` impl on `Meters` is the reflexive `From<Meters>`). In a generic signature the logic flips: `D: Into<Meters>` is satisfied by every `From` impl through the blanket impl and by any hand-written `Into` impl, while `Meters: From<D>` misses the latter. Hand-written `Into` impls survive mostly in older code: before Rust 1.41 the orphan rules rejected impls such as `impl<T> From<Wrapper<T>> for Vec<T>`, so authors wrote `Into` instead.

code

rust · 14 lines
rust
struct Meters(f64);
struct Feet(f64);
impl From<Feet> for Meters {
    fn from(f: Feet) -> Self { Meters(f.0 * 0.3048) }
}
// Accepts anything convertible into Meters, including Meters itself.
fn total<D: Into<Meters>>(parts: Vec<D>) -> Meters {
    Meters(parts.into_iter().map(|d| d.into().0).sum())
}
fn main() {
    let a = total(vec![Feet(10.0), Feet(5.0)]);
    let b = total(vec![Meters(2.0), Meters(0.5)]); // reflexive From<T> for T
    println!("{:.3} {:.1}", a.0, b.0);
}

go deeper

for a junior

Remember the rule as a pair: implement From, bound on Into. Be able to say which direction the blanket impl goes.

for a middle

Explain why an Into-only impl breaks Meters::from(feet) and why D: Into<Meters> accepts more callers than Meters: From<D>.

for a senior

In review, replace hand-written Into impls with From, challenge From impls that panic or lose data, and know that pre-1.41 orphan rules explain legacy Into impls.

for a principal

Treat the From impls on public types as an API surface: each one is permanent and inferred by callers through into, so admit only obvious, lossless conversions.

## The blanket impl runs in one direction `core::convert` defines `From<T>` (implemented on the target) and `Into<T>` (implemented on the source), and connects them with exactly one blanket impl: ```rust impl<T, U> Into<U> for T where U: From<T> { fn into(self) -> U { U::from(self) } } ``` There is **no** matching `impl<T, U> From<T> for U where T: Into<U>`. So: - `impl From<Feet> for Meters` produces `Meters::from(feet)` **and** `feet.into()`. - `impl Into<Meters> for Feet` produces `feet.into()` **only**. The module documentation states the rule plainly: as a library author you should always prefer implementing `From` or `TryFrom` over `Into` or `TryInto`, because they give the reverse trait "for free". The Rust API Guidelines put it more bluntly in C-CONV-TRAITS: `Into` and `TryInto` "should never be implemented". ## What an Into-only impl costs its callers With only `impl Into<Meters> for Feet`, the call `Meters::from(Feet(10.0))` fails to compile. rustc 1.99 reports **E0308**, mismatched types, "expected `Meters`, found `Feet`": in this example the only `From` impl on `Meters` is the reflexive `impl<T> From<T> for T`, which wants a `Meters` argument. Rustc even suggests the workaround, `Meters::from(Feet(10.0).into())`. Callers who reach for the `From` spelling — the natural one when nothing else names the target type — are stuck. Both spellings also feed `TryFrom`: core has `impl<T, U> TryFrom<U> for T where U: Into<T>` with `Error = Infallible`, so any infallible conversion is also usable where a fallible one is expected. ## Why generic bounds say Into The guidance flips for **consumers**. The `Into` documentation says to prefer `Into` over `From` when writing trait bounds "to ensure that types that only implement `Into` can be used as well". Compare two ways to accept "anything convertible to `Meters`": | Signature | Accepts a `From<Feet> for Meters` pair | Accepts an `Into<Meters> for Feet`-only type | Accepts `Meters` itself | |---|---|---|---| | `fn total<D: Into<Meters>>(parts: Vec<D>)` | yes, via the blanket impl | yes | yes, via the reflexive impl | | `fn total<D>(parts: Vec<D>) where Meters: From<D>` | yes | no | yes | `D: Into<Meters>` is the wider set, and the body reads the same: `d.into()` inside the function infers `Meters` from the bound. In practice the `Into` bound gives callers three things: - they may pass the target type itself, thanks to the reflexive `impl<T> From<T> for T`; - they may pass any type that gains a `From` impl later, in your crate or theirs, without the signature changing; - they never need a turbofish at the call site, because the parameter type fixes the conversion. A type with no conversion at all is still rejected at compile time: for `total(vec![1_u8])` rustc 1.99 reports E0277, the trait bound `Meters: From<u8>` is not satisfied. ## Why older code implements Into anyway Before **Rust 1.41** (January 2020) the orphan rules were stricter. The `Into` docs give the example `impl<T> From<Wrapper<T>> for Vec<T>`: converting a local generic wrapper into a foreign generic type was rejected, so authors wrote `impl<T> Into<Vec<T>> for Wrapper<T>` instead. The 1.41 release notes list the change ("You can now write `impl<T> From<Foo> for Vec<T> {}`"). On a current compiler that `From` impl is accepted, so a hand-written `Into` impl in a codebase today is usually a leftover worth replacing — the `From` docs say to implement `Into` only when targeting a release before 1.41. ## What a From impl should promise Choosing `From` over `Into` is the mechanical half. The `From` documentation also says when a conversion deserves `From` at all: 1. **Infallible** — if it can fail, use `TryFrom`; "don't provide a `From` impl that panics". 2. **Lossless** — `i32: From<u16>` exists, but `u16: From<u32>` does not, because the larger value may not fit. 3. **Value-preserving** — `f32: From<i16>` exists because `1_i16` and `1.0` are the same number; `String: From<u32>` does not, because a number and its text are different values (that is `Display`'s job). 4. **Obvious** — the only reasonable conversion; otherwise a named method such as `u32::from_le_bytes` is better. `Meters: From<Feet>` passes all four. `f64: From<i64>` is absent for the lossless reason: rustc 1.99 rejects it with E0277, while `f64: From<i32>` exists. ## Summary for a code review - Implement `From` (or `TryFrom`); fall back to a hand-written `Into` only where `From` cannot be implemented, as the `Into` docs put it. - Bound generic parameters on `Into<U>` (or `TryInto<U>`) to accept the widest set of callers. - Treat a surviving `impl Into` as a pre-1.41 artefact unless a `From` impl is genuinely impossible.

  • Is a `From` impl that panics on bad input acceptable?
    No. The `From` documentation says the conversion must not fail and explicitly says not to provide a `From` impl that panics; a conversion that can fail belongs in `TryFrom`, which returns a `Result` and lets the caller decide.
  • Why does std implement `From<i32>` for `f64` but not `From<i64>`?
    `From` is meant to be lossless. Every `i32` fits exactly in an `f64`'s 53-bit significand, but large `i64` values do not, so rustc 1.99 rejects `f64::from(5_i64)` with E0277. An `as` cast is the explicit, possibly rounding, alternative.
  • Does `D: Into<Meters>` let the function body call `d.into()` without an annotation?
    Yes. Inside the generic function the bound itself tells the compiler the target, so `d.into()` resolves to `Meters`; annotations are only needed where nothing in scope names the target type.

  • Implementing Into is equivalent to implementing From, since each derives the other.
  • A bound written as D: Into<U> accepts fewer types than U: From<D>.
  • You must implement Into whenever the target type comes from another crate.
  • From is fine for a lossy conversion such as u32 to u16 if it is documented.
  • An Into-only impl also lets callers write Target::from(value).

Assumes Rust 1.99 on edition 2024; the orphan-rule relaxation that removed the main reason to implement Into directly shipped in Rust 1.41.