Sub topic 10
From: defining a conversion
This chapter assumes you know structs, enums, impl Trait for Type, and the basics of ownership. It also assumes you have used String::from("text") at least once. Here you will see what that call does and how to add the same kind of conversion to your own types.
What From promises
From<T> is a standard library trait with one method, fn from(value: T) -> Self. If a type B implements From<A>, you can build a B from an A by calling B::from(a).
The trait carries an agreement about meaning, not only a signature:
- The conversion cannot fail.
fromreturnsSelf, not aResult. - The conversion takes its input by value, so it consumes the input.
- The conversion should be obvious and lossless. A reader should not be surprised by what comes out.
Conversions that can fail belong to TryFrom, which a later chapter covers.
Your first implementation
Here is a conversion between two newtype wrappers, which are tuple structs with one field.
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::from(boiling);
println!("{}", f.0);
}Note the direction. You write impl From<Source> for Target, and the code reads "Target can be made from Source." Beginners often reverse the two types. A reliable check is that Target::from(source) should read naturally at the call site.
After this impl, boiling has been moved into from. You cannot use it again unless the type is Copy.
The standard library already uses From
You have been calling From implementations all along.
fn main() {
let s = String::from("hello");
let big = i64::from(7i32);
let wide = f64::from(3u8);
let code = u32::from('A');
let boxed: Box<str> = Box::from("text");
println!("{} {} {} {} {}", s, big, wide, code, boxed);
}Each conversion here is lossless. Every i32 fits in an i64, and every u8 fits in an f64. The standard library offers From only where nothing can be lost, so i32::from(5i64) does not compile. For narrowing conversions you use TryFrom or an as cast.
| Expression | Compiles? | Why |
|---|---|---|
| `i64::from(5i32)` | Yes | Widening, no value is lost |
| `f64::from(5i32)` | Yes | Every `i32` is exactly representable |
| `i32::from(5i64)` | No | Narrowing can overflow |
| `f32::from(5i32)` | No | Large `i32` values lose precision |
| `u32::from('A')` | Yes | Every `char` fits in a `u32` |
Several From impls on one type
A type can implement From for many source types. Each impl is a separate trait, because From<A> and From<B> are different traits.
#[derive(Debug, PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl From<(i32, i32)> for Point {
fn from(t: (i32, i32)) -> Self {
Point { x: t.0, y: t.1 }
}
}
impl From<[i32; 2]> for Point {
fn from(a: [i32; 2]) -> Self {
Point { x: a[0], y: a[1] }
}
}
fn main() {
let a = Point::from((1, 2));
let b: Point = [3i32, 4].into();
assert_eq!(a, Point { x: 1, y: 2 });
println!("{:?} {:?}", a, b);
}The compiler picks the impl from the argument type. With Point::from(x), the type of x decides which impl runs. If the argument type is ambiguous, for example an untyped integer literal where several impls could match, the compiler reports an error. Add a type annotation to fix it.
Borrowed and owned inputs
from consumes its argument, so decide whether you want to accept borrowed data, owned data, or both. If you accept an owned String, you can reuse its allocation. If you accept &str, you must copy.
#[derive(Debug)]
struct Name(String);
impl From<&str> for Name {
fn from(s: &str) -> Self {
Name(s.to_string())
}
}
impl From<String> for Name {
fn from(s: String) -> Self {
Name(s)
}
}
fn main() {
let a = Name::from("ada");
let owned = String::from("grace");
let b = Name::from(owned);
println!("{:?} {:?}", a, b);
}The String impl does no copying. It takes over the buffer the caller already allocated. Offering both impls lets callers pick the cheaper path.
What the compiler gives you in return
You write only From. The standard library then provides other things based on it.
Because the diagram fence must follow the exact format, here it is in the required form.
The second path is the Into trait, which the next chapter covers. For now, remember that Into is a consequence of From. The standard library has a blanket implementation, impl<T, U: From<T>> Into<U> for T, so every From impl creates an Into impl in the opposite direction.
The standard library also has a reflexive impl, impl<T> From<T> for T. Every type can be converted to itself. This explains the next error.
Common errors
Implementing Into instead of From. It is legal but almost never right. You lose the From impl and the ? operator support described in a later chapter. Implement From and take Into for free.
Writing impl From<T> for T. This conflicts with the reflexive impl. The compiler reports "conflicting implementations of trait From<T>". You do not need to write this conversion, because it already exists.
Breaking the orphan rule. You may implement a trait only if the trait or at least one involved type is local to your crate.
struct Meters(f64);
// Allowed: Meters is local, so it can be the From parameter.
impl From<Meters> for String {
fn from(m: Meters) -> Self {
format!("{} m", m.0)
}
}
// Not allowed: neither u8 nor String is local.
// impl From<u8> for String { ... }
fn main() {
let s = String::from(Meters(2.5));
println!("{}", s);
}Hiding failure inside from. If your conversion can fail, do not call unwrap or panic! inside from. Use TryFrom so the caller sees the failure in the type.
Choosing between From and a constructor
Use From when the conversion is natural, cheap to explain, and has one obvious result for the given source type. Use a named function like Point::from_polar(r, theta) when:
- Several different meanings could apply to the same input type, such as
f64as radians or as degrees. - The conversion needs extra parameters.
- The conversion can fail or loses information.
A good test is whether you could describe the conversion in one short sentence without the word "depending."
Summary of the working model
impl From<A> for BdefinesB::from(a: A) -> B.- The conversion is infallible, takes ownership of
a, and should preserve meaning. - The standard library derives
Into<B> for Afrom it automatically. - You can write many
Fromimpls for one target type, one per source type. - The orphan rule limits which combinations you may write.
Exercise
Write a Rgb struct with three u8 fields named r, g, and b, and implement From<(u8, u8, u8)> for it. Then write one line that builds a Rgb from the tuple (255, 128, 0) by calling from.
Show answer
Define struct Rgb { r: u8, g: u8, b: u8 }, then impl From<(u8, u8, u8)> for Rgb { fn from(t: (u8, u8, u8)) -> Self { Rgb { r: t.0, g: t.1, b: t.2 } } }. The call is let orange = Rgb::from((255, 128, 0));. The double parentheses are needed because the argument is a single tuple.
Exercise
Why does impl From<u8> for String fail to compile in your own crate, while impl From<Meters> for String compiles when Meters is defined in your crate?
Show answer
The orphan rule requires that either the trait or at least one of the types in the impl is local to your crate. From, u8, and String all come from the standard library, so the first impl has nothing local. In the second impl, Meters is local and appears as the trait parameter, so the impl is allowed.