Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 132 ยท Structs, Enums and Traits Basics

Display, From and Standard Conversion Traits

Learn Rust conversion traits: Display and ToString, From and Into, TryFrom, FromStr, AsRef, Default and hand-written PartialEq and PartialOrd.

You have already used a few standard traits without thinking much about them: {:?} works because of Debug, and .clone() works because of Clone. A handful of other traits show up in almost every Rust program because they answer very ordinary questions. How do I print this type for a human? How do I turn a &str into my type? How do I convert one number into another without losing data? How do I accept "anything that looks like a string" in a function?

This lesson tours the traits that answer those questions: Display and ToString, From and Into, TryFrom and TryInto, FromStr, AsRef, Default, and the comparison traits PartialEq and PartialOrd written by hand. They all build on traits, and implementing them is how your own types start to feel like part of the language. Operator overloading continues the idea with +, - and [].

Display: printing for humans

{:?} uses the Debug trait, which is meant for programmers and can be derived. {} uses Display, which is meant for end users and which you must write yourself, because only you know how a Temperature or an Invoice should look.

Rust
use std::fmt;

struct Celsius(f64);

impl fmt::Display for Celsius {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:.1} ยฐC", self.0)
    }
}

The method gets a Formatter, which is a place to write characters into. You use the write! macro exactly like println!, but the first argument is the formatter. The method returns fmt::Result, so you normally let write! produce it as the last expression.

Rust Implementing Display

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

ToString comes for free

Once a type implements Display, the standard library gives it .to_string() automatically through a blanket implementation (more on those in Trait bounds). You should never implement ToString yourself: implement Display and you get both. The result is an owned String, which is handy for padding, as the last line of the example shows.

Width and alignment such as {:>12} are not applied automatically to your Display output. A plain write! ignores them. That is why the example converts to a String first, and why the next section shows f.pad.

Honouring format flags

If you want {:>12} or {:<8} to work on your own type, hand the finished text to f.pad, which applies width, fill, alignment and precision for you. You can also look at flags such as f.alternate() (the # flag) to offer a second layout.

Rust Display with padding and the alternate flag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Display versus Debug

Use #[derive(Debug)] on nearly everything, because it costs nothing and helps in tests and logs. Implement Display only when there is one obvious human-readable form. Do not make Display output something a program must parse back; that is the job of FromStr, covered below.

From and Into: infallible conversions

From<T> says "I can build myself from a T, and it cannot fail". You implement From, and Into appears for free in the other direction: if B: From<A> then A: Into<B>.

Rust
impl From<(i32, i32)> for Point {
    fn from(pair: (i32, i32)) -> Point {
        Point { x: pair.0, y: pair.1 }
    }
}

After that, both Point::from((1, 2)) and let p: Point = (1, 2).into(); work. Always implement From, never Into: it is the one that the rest of the ecosystem expects, and it gives you Into anyway.

Rust From and Into

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The standard library is full of From impls: String::from("x"), i64::from(some_i32), Vec::from([1, 2, 3]), Box::from(...), f64::from(some_i32). Numeric From impls exist only for lossless widenings. There is From<i32> for i64 but no From<i64> for i32, because that could lose data. For those you need TryFrom.

From and the ? operator

From has one more important job. When you write ? on a Result, a failing error value is passed through From::from to convert it into the error type of your function. That is how one function can use ? on both a parse error and an I/O error and return a single error enum. Custom error types shows this in detail; here is a small taste.

Rust From powering the question mark

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TryFrom and TryInto: conversions that can fail

When a conversion might not work, use TryFrom. It has an associated Error type and returns a Result. Narrowing integer conversions are the classic case, and your own validated types are the other.

Rust TryFrom for numbers and for your own type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

TryFrom and TryInto are in the prelude since the 2021 edition, so the use line above is optional in this course; it is shown to make the origin clear. If you write x as u8 instead, Rust silently truncates, which is the very bug try_from prevents. See scalar types for the casting rules.

FromStr: parsing text into your type

"42".parse::<i32>() works because i32 implements FromStr. Implement the same trait and .parse() works on your type too. The method is from_str(s: &str) -> Result<Self, Self::Err>.

Rust Implementing FromStr

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Notice the pairing: Display turns a value into text, FromStr turns text back into a value. When both exist, value.to_string().parse() should give back an equal value. That round trip is a good property to test.

AsRef and Borrow: accept many shapes of the same thing

Suppose a function wants to read a name. Taking &str forces callers with a String to write &name, which is fine, but a function that should also accept &String, Box<str> or a Cow can ask for impl AsRef<str>. AsRef<T> is a cheap reference-to-reference conversion: as_ref() gives you a &T.

Rust AsRef for flexible arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Borrow looks similar but carries an extra promise: the borrowed form must hash and compare exactly like the owned form. That promise is what lets a HashMap<String, V> be searched with a &str. You will mostly meet Borrow as a bound inside standard collections (HashMap), and use AsRef in your own APIs.

Use impl AsRef<str> or impl Into<String> in public function signatures only when the flexibility is real. Each generic parameter is compiled once per type (see Generics), so for a private helper a plain &str is simpler and just as fast.

Default: a sensible starting value

Default gives a type a zero-like value, and #[derive(Default)] builds it from the defaults of the fields. It works for structs whose fields all implement Default: numbers are 0, bool is false, String and Vec are empty, Option is None.

When the derived value is not what you want, implement it by hand, and use struct update syntax to override a few fields.

Rust Default and struct update syntax

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

#[derive(Default)] also works on enums if you mark one unit variant with #[default].

PartialEq and PartialOrd by hand

#[derive(PartialEq)] compares every field and #[derive(PartialOrd)] compares fields in order, top to bottom. Often that is wrong for your domain. A case-insensitive tag or a version number needs its own rule. Then you write the traits yourself: eq returns a bool, and partial_cmp returns Option<Ordering>.

Rust Writing PartialEq and PartialOrd by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The "partial" in both names is real: floating-point NAN is not equal to itself, and it has no order against other numbers, so f64 implements only the partial traits. The full Eq and Ord traits add the promise of reflexivity and a total order. Operator overloading explains how to move from the partial traits to the full ones and why Ord is needed for sorting and BTreeMap keys.

Common mistakes

Forgetting to implement Display and then printing with {} is the first error almost every learner meets.

Rust Printing without Display (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler stops with error[E0277]: \Point` doesn't implement `std::fmt::Display``, and a note saying that in format strings you may be able to use {:?} (or {:#?} for pretty-print) instead. The fix is to implement Display as shown earlier. The second common mistake is writing impl Into<Target> for Source by hand; the compiler accepts it, but you lose the automatic From and the ? conversion. Implement From instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which trait should you implement to make println!("{}", value) work for your type?

    {} uses Display. ToString is provided automatically once Display exists, and Debug is what {:?} uses.
  2. 2. You implement From<A> for B. What do you get for free?

    A blanket implementation turns every From<A> for B into Into<B> for A, which is why you implement From and never Into.
  3. 3. Why is there no From<i64> for i32?

    From is for conversions that cannot fail. A 64-bit value may not fit into 32 bits, so the standard library offers i32::try_from(x), which returns a Result.
  4. 4. What does FromStr make possible?

    str::parse is generic over any F: FromStr, so implementing FromStr for your type enables "text".parse::<YourType>().
  5. 5. Why does f64 implement PartialOrd but not Ord?

    NAN is neither less than, equal to nor greater than any number, so floats have no total order. partial_cmp returns None for such comparisons.

Summary

  • Implement Display for human-readable output; you get .to_string() automatically. Use f.pad to honour width and alignment.
  • Implement From<A> for B for infallible conversions; Into and ? error conversion come for free.
  • Use TryFrom and TryInto when a conversion can fail, such as narrowing integers or validating input.
  • Implement FromStr so .parse() works on your type; it is the mirror image of Display.
  • AsRef lets a function accept several string-like or slice-like types; Borrow is the stricter cousin used by maps.
  • Default provides a starting value; derive it, or write it and use ..Default::default().
  • Write PartialEq and PartialOrd by hand when the derived field-by-field rule is wrong for your domain.

Next: Operator Overloading