Sub topic 11
Into: calling a conversion from the other side
This chapter assumes you know impl Trait for Type, generics with trait bounds, and the From trait from the previous chapter. Here you will see how Into relates to From, when to use each, and how to take impl Into<T> as a parameter.
Into comes from From
From<T> defines how to build a value from a T. Into<U> describes the same conversion as a method on the source value. The standard library connects them with one blanket implementation:
impl<T, U> Into<U> for T
where
U: From<T>,
{
fn into(self) -> U {
U::from(self)
}
}Every type T gets .into() for each target U where U: From<T>. You write one impl From<A> for B. Both B::from(a) and a.into() then work.
struct Celsius(f64);
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 a: Fahrenheit = Fahrenheit::from(Celsius(100.0));
let b: Fahrenheit = Celsius(0.0).into();
println!("{} {}", a.0, b.0);
}This prints 212 32. The two conversion lines run the same code.
Implement From, not Into
The usual rule is to implement From and let Into follow. The reverse does not hold. If you write only impl Into<B> for A, the type B does not get From<A>, and you lose B::from(a) and the ? operator's automatic conversion.
Before Rust 1.41, the orphan rule sometimes forced impl Into<Foreign> for Local, because impl From<Local> for Foreign was rejected. The rule has since been relaxed. A local type as the generic parameter now satisfies it. Today, implementing Into directly is rarely the right choice.
The inference trap
from names its target type: Fahrenheit::from(c). into does not. The compiler must work out the target from context. If it can't, you get an error such as "type annotations needed".
struct Celsius(f64);
struct Fahrenheit(f64);
impl From<Celsius> for Fahrenheit {
fn from(c: Celsius) -> Self {
Fahrenheit(c.0 * 9.0 / 5.0 + 32.0)
}
}
fn show(f: Fahrenheit) {
println!("{}", f.0);
}
fn main() {
// let f = Celsius(37.0).into(); // error: type annotations needed
let f: Fahrenheit = Celsius(37.0).into(); // annotation on the binding
show(f);
show(Celsius(100.0).into()); // inferred from the parameter type
}Three places commonly supply the target type:
- A type annotation on the
letbinding. - A function parameter type, as in
show(Celsius(100.0).into()). - A return type, as in a function that ends with
value.into().
Calling a method on the result of .into() is a common source of this error. The compiler can't look up methods on a type it hasn't determined yet.
fn main() {
// let n = "hello".into().len(); // error: type annotations needed
let s: String = "hello".into();
println!("{}", s.len());
}Accepting impl Into in function parameters
The most useful application of Into is as a bound. A function that needs a String can accept anything convertible to one:
struct User {
name: String,
}
impl User {
fn new(name: impl Into<String>) -> Self {
User { name: name.into() }
}
}
fn main() {
let a = User::new("ada");
let b = User::new(String::from("grace"));
println!("{} {}", a.name, b.name);
}This prints ada grace. Callers can pass a &str or a String without writing .to_string() at the call site. The standard library has From<&str> for String and the reflexive From<T> for T, so both compile.
impl Into<String> is shorthand for a generic parameter. This form is equivalent, and you need it when you want to name the type or reuse it:
fn total_len<T: Into<String>>(items: Vec<T>) -> usize {
items
.into_iter()
.map(|t| {
let s: String = t.into();
s.len()
})
.sum()
}
fn main() {
println!("{}", total_len(vec!["ab", "cde"]));
}This prints 5. Inside the closure, the annotation let s: String is required. Without it, t.into().len() hits the inference trap from the previous section.
What the conversion costs
into takes self by value. The cost depends on the types involved:
| Call | What happens |
|---|---|
| `String` into `String` | The value moves. No copy and no allocation. |
| `&str` into `String` | Allocates a new `String` and copies the bytes. |
| `Celsius` into `Fahrenheit` | Runs your `from` body. |
The reflexive impl is why impl Into<String> costs nothing when the caller already owns a String. A plain &str parameter would force every caller with a String to borrow it, and the function would then copy it again. That is the case where impl Into<String> saves an allocation.
When not to use Into bounds
- Many call sites with different types. Each distinct
Tproduces its own compiled copy of the function (monomorphization). This is a minor cost, but it adds up in large generic APIs. For a hot or widely used function, you can write a thin generic wrapper that callsname.into()and then forwards to a non-generic inner function. - The function only reads the data. Take
&str. AnInto<String>bound is for functions that need to own the value. - Several
Fromimpls make the target ambiguous. Inside a generic function the target is fixed by the bound, so this is not a problem there. At a call site withlet x = a.into();it is.
Into and the ? operator
The ? operator converts errors with From, not with a method you call. When ? sees an Err(e), it returns Err(From::from(e)) from the enclosing function. The error type you declare in the signature is the target. You never write .into(), and you implement From<SourceError> for YourError. The next chapter covers this in detail.
Common errors
- Type annotations needed. Add a binding annotation, pass the value where a type is expected, or call
Target::from(x). - Using the value after
into().intoconsumesself. If you need the original afterward, clone it first, or implementFrom<&T>for a borrowed conversion. - Conflicting implementations.
impl<T> From<T> for MyTypeconflicts with the standard library'sFrom<T> for T, so it will not compile. - Wanting
Frombut having onlyInto. If a foreign type's conversion is only available throughInto, you cannot callTarget::from.
Exercise
Given struct Meters(f64); and impl From<f64> for Meters { fn from(v: f64) -> Self { Meters(v) } }, write a function fn describe(d: impl Into<Meters>) -> String that returns the text "N meters", where N is the inner value. Then say which call forms work for describe and why. Also explain why let m = 5.0.into(); fails.
Show answer
Body: let m: Meters = d.into(); format!("{} meters", m.0). describe(2.5) works because Meters: From<f64> gives f64: Into<Meters>. describe(Meters(2.5)) also works, because of the reflexive From<T> for T. describe("x") does not compile, since no From<&str> for Meters exists. let m = 5.0.into(); fails because the compiler can't tell which target type you want. Annotate the binding (let m: Meters = 5.0.into();) or use Meters::from(5.0).