In Rust, after you write `impl From<Celsius> for Fahrenheit`, why does `let f: Fahrenheit = c.into();` also compile?
answer
- one impl, two spellings
- a blanket impl in core
- Into<U> for T where U: From<T>
- into needs a known target type
basics
~20 sCore has a blanket impl, Into<U> for T where U: From<T>, so implementing From<Celsius> for Fahrenheit gives Celsius an into() that calls Fahrenheit::from. The compiler only needs the target type, here from the let annotation.
solid answer
~30 sThe standard library contains `impl<T, U> Into<U> for T where U: From<T>`, whose `into` just calls `U::from(self)`. So one `impl From<Celsius> for Fahrenheit` gives two spellings: `Fahrenheit::from(c)` and `c.into()`. Because `into` is generic over its target, the compiler has to learn that target from context: a `let` annotation, a parameter type or a return type. Several types implement `From<Celsius>` (at least `Fahrenheit` and, through the reflexive `impl<T> From<T> for T`, `Celsius` itself), so `let f = c.into();` fails with E0283, "type annotations needed". Both spellings take `c` by value, so a non-`Copy` `Celsius` is moved and any later use is E0382.
code
rust · 19 lines#[derive(Debug, Clone, Copy, PartialEq)]
struct Celsius(f64);
#[derive(Debug, Clone, Copy, PartialEq)]
struct Fahrenheit(f64);
impl From<Celsius> for Fahrenheit {
fn from(c: Celsius) -> Self {
Fahrenheit(c.0 * 9.0 / 5.0 + 32.0)
}
}
fn main() {
let boiling = Celsius(100.0);
let a = Fahrenheit::from(boiling);
let b: Fahrenheit = boiling.into(); // Into comes from std's blanket impl
println!("{a:?} {b:?}");
assert_eq!(a, b);
}go deeper
Recall the blanket impl in one sentence: implement From on the target type and Into appears for the source type. Know that into needs a target named somewhere.
Explain why let f = c.into(); fails with E0283 while Fahrenheit::from(c) compiles, and that both calls move a non-Copy source.
Spot redundant Into impls in review (E0119), choose from or into by whether the context already names the type, and offer From<&T> when consuming the source is wasteful.
Frame conversions as part of a type's public API: each From impl is a promise callers will lean on through into, so keep the set small and obvious.
## Two traits, one implementation Rust's standard library has a pair of traits for **infallible, consuming conversions**, both in `core::convert` and both in the prelude: - `From<T>` has one required function, `fn from(value: T) -> Self`. You implement it on the **target** type: `impl From<Celsius> for Fahrenheit` says "a `Fahrenheit` can be built from a `Celsius`". - `Into<T>` has one required method, `fn into(self) -> T`. It is written from the **source** type's side: `Celsius: Into<Fahrenheit>` says "a `Celsius` can be turned into a `Fahrenheit`". They describe the same conversion from opposite ends, so the library makes one follow from the other. ## The blanket impl that connects them `core/src/convert/mod.rs` contains this implementation (shown without its attributes): ```rust impl<T, U> Into<U> for T where U: From<T>, { fn into(self) -> U { U::from(self) } } ``` A **blanket impl** is an implementation for every type that meets a bound. This one says: for any pair of types where `U: From<T>` holds, `T: Into<U>` holds as well, and `into` does nothing except call `from`. Once you write `impl From<Celsius> for Fahrenheit`, the bound is satisfied for `T = Celsius, U = Fahrenheit`, so `c.into()` resolves to `Fahrenheit::from(c)`. You write no `Into` code at all. The module also has a **reflexive** impl, `impl<T> From<T> for T`, which returns its argument unchanged. Every type can therefore be converted "into" itself. ## Why into() needs to know its target `into` is generic over the output type, and the receiver alone does not fix it. The compiler looks for the target in the surrounding code: 1. a type annotation on the binding, as in `let f: Fahrenheit = c.into();` 2. the parameter type of a function the result is passed to, as in `print_temp(c.into())` 3. the declared return type when `c.into()` is the tail expression of a function 4. a field type in a struct literal, as in `Reading { temp: c.into() }` Without any of these, rustc 1.99 rejects `let f = c.into();` with **E0283**, "type annotations needed", and notes that "the type must implement `From<Celsius>`". At least two types qualify — `Fahrenheit`, and `Celsius` itself through the reflexive impl — and rustc does not pick one. `Fahrenheit::from(c)` never has this problem because the target is written in the call. That is the practical rule: use `T::from(x)` where nothing else names the type, and `x.into()` where the context already does. ## Both spellings consume the source `From::from` takes `value: T` and `Into::into` takes `self`, both **by value**. Calling either moves the argument: | Code | Effect on `c` | |---|---| | `Fahrenheit::from(c)` | moved, unless `Celsius: Copy` | | `c.into()` | moved, unless `Celsius: Copy` | | `Fahrenheit::from(&c)` | borrowed, but only if you wrote `impl From<&Celsius> for Fahrenheit` | For a non-`Copy` `Celsius`, using `c` after `c.into()` fails with **E0382**, "borrow of moved value", and rustc adds a note that `into` "takes ownership of the receiver `self`". A small newtype over `f64` can simply `#[derive(Clone, Copy)]`, in which case the call copies and `c` stays usable. When the source is expensive to copy and you only need to read it, implementing `From<&Celsius>` is a legitimate second impl. ## Conversions you already use The same blanket impl powers conversions every Rust programmer has written, all of them plain `From` impls in the standard library: - `String::from("text")` and `let s: String = "text".into();` — `String: From<&str>` - `Vec::from([1, 2, 3])` — `Vec<T>: From<[T; N]>` - `let b: Box<str> = "x".into();` — `Box<str>: From<&str>` - `PathBuf::from(String::from("/tmp"))` — `PathBuf: From<String>` - `u64::from(7_u32)` — a widening integer conversion that cannot lose information None of these types implements `Into` by hand; each `into()` call on them goes through the one blanket impl described above. Writing `From<Celsius> for Fahrenheit` puts your units library on exactly the same footing. ## Rust never applies From on its own A `From` impl does not create an implicit conversion. Assigning a `Celsius` to a `Fahrenheit` variable, or passing one where a `Fahrenheit` parameter is expected, is still a type mismatch until you call `from` or `into`. The one operator that inserts a `From::from` call for you is `?`, which converts an error value; that belongs with the error-handling material, not here. ## Mistakes worth catching in review - Writing an `impl Into<Fahrenheit> for Celsius` next to the `From` impl: it is rejected as **E0119**, conflicting implementations, because the blanket impl already provides it. - Expecting `let f = c.into();` to infer `Fahrenheit` "because that is the only impl I wrote". - Assuming `into()` borrows its receiver because it is called with method syntax. - Treating `From` as an implicit coercion that kicks in at assignments.
- Can you implement both `From<Celsius> for Fahrenheit` and `Into<Fahrenheit> for Celsius` in the same crate?No. The second impl is rejected with E0119, conflicting implementations of `Into<Fahrenheit>` for `Celsius`, and rustc points at core's `impl<T, U> Into<U> for T where U: From<T>`. Once the `From` impl exists, the `Into` impl already exists too.
- How do you convert a non-`Copy` `Celsius` without giving it away?Implement `From<&Celsius> for Fahrenheit` and call `Fahrenheit::from(&c)` or `(&c).into()`; the reference is consumed, not the value. For a tiny newtype over `f64`, deriving `Clone` and `Copy` is simpler: the conversion then copies the value and `c` stays usable.
- You must write an Into impl yourself for every From impl you add.
- c.into() infers its target because only one From impl was written.
- Calling c.into() only borrows c, so c is still usable afterwards.
- Rust applies From conversions implicitly at assignments and function calls.
- Into is a method that the From trait provides to implementors.