Sub topic 11
Into: calling a conversion from the other side
This chapter assumes you know how impl Trait for Type works, how ownership moves values, and how From is defined. Here you will see how Into relates to From and how to use it in your own code.
The relationship between From and Into
Into<T> is a standard trait with one method, into(self) -> T. You almost never implement it by hand. The standard library has a blanket implementation, which is one generic impl that covers every type that qualifies:
impl<T, U> Into<U> for T
where
U: From<T>,
{
fn into(self) -> U {
U::from(self)
}
}If U: From<T>, then T: Into<U> holds automatically. Write the From impl once and both call styles 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 boiling = Celsius(100.0);
let f: Fahrenheit = boiling.into();
println!("{}", f.0);
}This prints 212. The call boiling.into() consumes boiling and returns a Fahrenheit.
Why the target type must be known
into() does not name its result type. The compiler infers it from context. If it cannot, you get an error such as "type annotations needed".
fn main() {
let a: String = "hello".into();
let b = String::from("hello");
println!("{} {}", a, b);
}The annotation on a tells the compiler which From impl to use. Without it, "hello".into() could target several types. Function arguments, return types, and struct fields also supply that context.
Using Into in function parameters
The most common use of Into is in a bound on a parameter. The function then accepts anything convertible to the type it needs:
fn greet(name: impl Into<String>) {
let name: String = name.into();
println!("Hello, {}!", name);
}
fn main() {
greet("Ada");
greet(String::from("Grace"));
}A caller can pass a &str, which gets allocated into a String, or an owned String, which is moved in with no extra copy. This works well for constructors that must own their data.
From or Into: which to implement
Implement From. Because of the blanket impl, you get Into for free. Implementing Into directly is only needed in rare cases, such as converting into a type defined in another crate where the orphan rule blocks a From impl. Use Into in trait bounds, because it is the more general bound. T: Into<U> is satisfied by any From impl, and by any manual Into impl as well.
Two things to remember:
into()takesselfby value, so the original is moved. Clone first if you still need it.- A generic
Intoparameter makes the compiler generate one copy of the function per type you call it with. For hot paths with a single type, a concrete parameter is simpler.
Exercise
A function is declared as fn open(path: impl Into<String>). Which of these calls compile: open("a.txt"), open(String::from("a.txt")), open(42)? Explain why.
Show answer
The first two compile. String implements From<&str> and From<String> (the latter through the reflexive From<T> for T), so &str and String both implement Into<String>. String has no From<i32> impl, so open(42) fails to compile.