Module 9 · Lesson 23 of 112

Conversion and operator traits

Implement Rust conversions, formatting, and operator traits with explicit rules for ownership, validation, and comparison.

  • Beginner to advanced
  • 10 min read
  • 23 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM, a stable Rust toolchain, and Cargo

Your place in the module
By the end you can 4 objectives
  • Choose between From, TryFrom, AsRef, and AsMut for a given API.
  • Implement Display and From<&str> and verify that a value survives a text round trip.
  • Implement Add and keep PartialEq and PartialOrd consistent.
  • Identify the trait behind dereferencing, iteration, cleanup, and closure calls.
Video coming soonConversion and operator traits
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Trait bounds, impl Trait, and trait objects
  • Trait bounds specify the operations generic code can use.
  • Each return-position impl Trait denotes a single hidden concrete type for a given instantiation.
  • A trait object pointer carries a data pointer and a vtable pointer.
01

Owned conversions and borrowed views

4 min read

You saw trait objects and the vtable. This lesson answers how to implement the conversion and operator traits by hand.

A Linux program that opens a device node has two separate jobs. It needs to pass a pathname to the open operation, and Linux needs to resolve that pathname and check whether the open can succeed. Rust's std::fs::File::open takes an argument bounded by AsRef<Path>, so it can borrow a path from different argument types. Obtaining that view succeeds even when the file is missing. The attempt to open the file can still fail. The distinction matters when you design your own APIs. A conversion may supply the representation an operation needs, while the operation itself has separate rules for success. path_resolution(7), open(2)

Start with a type that owns a device label. In this example every &str is a valid label, including the empty string. The conversion preserves the input text exactly. A String lets the label keep its text after the original borrow ends.

rust
#[derive(Debug, PartialEq, Eq)]
struct DeviceLabel(String);

impl From<&str> for DeviceLabel {
    fn from(text: &str) -> Self {
        Self(text.to_owned())
    }
}

impl AsRef<str> for DeviceLabel {
    fn as_ref(&self) -> &str {
        self.0.as_str()
    }
}

A derive macro generates an implementation at compile time. Here Debug formats the struct and its field for inspection, and PartialEq compares that field. Eq records that equality is reflexive for this type, which is appropriate for string equality. The two handwritten implementations make decisions specific to this API. From<&str> chooses to copy text into owned storage. AsRef<str> chooses to expose that stored text through a shared reference. A derive and a handwritten implementation of the same trait for the same type would conflict, so remove the corresponding derive when you supply your own implementation.

DeviceLabel::from("sensor-a") names the destination directly. let label: DeviceLabel = "sensor-a".into(); expresses the same conversion using the destination type from the assignment. The standard library supplies the blanket implementation impl Into<U> for T where U: From<T>. Its into(self) calls U::from(self). This is why a second impl Into<DeviceLabel> for &str would conflict. A manual Into<U> would define fn into(self) -> U on the source type. Prefer defining From<T> on the destination when the orphan rule permits it. A manual Into is an option only where an implementation is permitted and no blanket implementation already applies.

When writing a generic function that needs an owned DeviceLabel, a bound such as impl Into<DeviceLabel> expresses what the function needs from its input. Inside the function, calling .into() produces the owned label. At a call site with several possible conversion destinations, a type annotation or a call to DeviceLabel::from makes the intended result explicit. In this example .into() takes a &str by value, so the conversion receives the reference and copies its text. If the source were an owned String, taking that source by value would let an implementation move the string into the wrapper.

Conversion contractsTraitsResultValue conversionFrom / IntoDestinationvalueCheckedconversionTryFrom /TryIntoValue orerrorShared viewAsRefSharedreferenceMutable viewAsMutMutablereference
Choose the trait by the result you need and whether the operation can reject an input.

Use TryFrom when rejection belongs to the conversion itself. For example, u8::try_from(raw) can convert a u16 register value only if it fits in a byte. With raw equal to 256_u16, the result is an error. A manual impl TryFrom<Source> for Destination defines type Error and fn try_from(value: Source) -> Result<Self, Self::Error>. The standard library supplies TryInto in the reverse calling direction, so let byte: Result<u8, _> = raw.try_into(); requests the same checked conversion. Choose one conversion contract for a given source and destination. Providing From already makes a corresponding infallible TryFrom available through blanket implementations.

AsRef<T> and AsMut<T> express cheap conversions between reference types. AsRef::as_ref(&self) returns &T, so let text: &str = label.as_ref(); lets a caller inspect the label while the label retains ownership. AsMut::as_mut(&mut self) returns &mut T. A wrapper around [u8; 4] could implement AsMut<[u8]> with fn as_mut(&mut self) -> &mut [u8] { &mut self.0 }. A caller could then pass the returned slice to a function that fills the buffer. Each trait requires its own implementation. Before offering a mutable view, check that all changes allowed through it preserve the wrapper's guarantees.

02

Formatting, parsing, and defaults

3 min read

Display defines what {} writes when you format a value. For DeviceLabel, choose the original text as its display representation. That makes the label useful in a log message and makes its displayed text suitable for reconstructing the value. Debug defines what {:?} writes. It can include a type name and field names or show details that help a developer inspect a value. Both traits take a mutable formatter and return fmt::Result, which lets the formatting destination report a write failure.

rust
use std::fmt;
use std::str::FromStr;

impl fmt::Display for DeviceLabel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.0.as_str())
    }
}

impl FromStr for DeviceLabel {
    type Err = std::convert::Infallible;

    fn from_str(text: &str) -> Result<Self, Self::Err> {
        Ok(Self::from(text))
    }
}

Use this block alongside the preceding type definition. Display has no built-in derive, so the implementation states exactly which text to write. The standard library implements ToString for displayable types, which makes label.to_string() available and gives you an owned String. The call "sensor-a".parse::<DeviceLabel>() uses FromStr. Its signature always returns a Result, and Infallible expresses that this particular parser accepts every string. The parser delegates to From so both input methods preserve text according to the same rule.

If a type accepts only a defined text format, implement FromStr with an error type that describes a rejected input. A label type that requires nonempty text would need a different conversion contract from DeviceLabel. It could implement TryFrom<&str> for explicit conversions and call that implementation from FromStr to reuse validation. Parsing receives a borrowed string and returns a value of the chosen type. For this owning wrapper, the output can outlive the string it was parsed from.

For Debug, the derive in the first example is enough. To choose a custom representation, remove Debug from the derive list and implement fmt::Debug with the same fmt signature as Display. For example, f.debug_tuple("DeviceLabel").field(&self.0).finish() writes a tuple-style diagnostic using the string's Debug representation. That representation makes escapes and quotation marks visible when inspecting whitespace or control characters. For a wrapper that stores credentials, a manual implementation could instead omit the sensitive field from diagnostic output.

A label text round tripBorrowedtextConstructlabelFrom<&str>Render textDisplay viato_stringParse textFromStr viaparseComparelabelsPartialEqBorrowedtextConstructlabelFrom<&str>Render textDisplay viato_stringParse textFromStr viaparseComparelabelsPartialEq
Display produces the text that the constructor or parser reads back.

A round trip tests both the text contract and the reconstruction. Given the definitions above, this test checks that conversion and display preserve spaces and that parsing the displayed string recreates the same value. Use rendered.as_str() when handing the resulting String back to DeviceLabel::from, since the implementation receives &str.

rust
#[test]
fn label_round_trip() {
    let original = DeviceLabel::from(" sensor-a ");
    let rendered = original.to_string();

    assert_eq!(rendered, " sensor-a ");
    assert_eq!(DeviceLabel::from(rendered.as_str()), original);
    let parsed: DeviceLabel = rendered.parse().unwrap();
    assert_eq!(parsed, original);
}

Checking the exact text catches an accidental change such as adding quotation marks or trimming spaces. Checking equality after reconstruction catches conversions that disagree about what the text represents. The derived PartialEq provides the equality check, and the derived Debug lets assert_eq! report the values if they differ. Display and FromStr are independent traits. A round trip is a contract you choose for a particular type and verify in a test.

Default defines how to construct a value when the caller provides no settings. Derive it on a struct when the defaults of all its fields produce the intended value. For the label wrapper, deriving Default would produce an empty string. If a separate configuration struct has a poll_interval_ms: u32 field and the program's chosen starting interval is 1000, write impl Default for Config with fn default() -> Self { Self { poll_interval_ms: 1000 } }. Deriving would use u32::default(), which is zero. A handwritten default is appropriate when the type has a specific initial configuration or when its fields need to be initialized together to produce a valid value.

03

Operators and other trait-driven syntax

4 min read

Add defines what left + right does for values of the types in the implementation. In Add<Rhs>, Rhs is the right operand type and defaults to Self. The associated type Output specifies what the expression produces. The add(self, rhs) method takes its operands by value for the operand types you choose. Implementing it for two owned values and implementing it for references are separate choices.

rust
use std::ops::Add;

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
struct SampleCount(u32);

impl Add for SampleCount {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        Self(self.0.saturating_add(rhs.0))
    }
}

Here SampleCount(2) + SampleCount(3) produces SampleCount(5). Saturation means any sum beyond u32::MAX produces SampleCount(u32::MAX). This example chooses that policy for a cumulative counter that stops increasing at the representable limit. If callers need to detect overflow, a named checked_add method returning Option<Self> makes the failure visible at the call site. Add can also accept a different operand type, such as Add<u32>, when adding a plain integer has a clear meaning and unit. The output type can differ from either operand.

PartialEq::eq(&self, other: &Rhs) defines ==, and its default ne method supplies !=. PartialOrd::partial_cmp(&self, other: &Rhs) returns Option<Ordering> and supplies the default behavior for <, <=, >, and >=. Some(Ordering::Equal) must agree with equality, and None represents a pair that has no ordering. The numeric field in SampleCount supports a total ordering, so deriving the comparison traits together gives consistent comparisons.

For a manual comparison, decide what the type represents before choosing the fields. Suppose a measurement has a timestamp and a value, and equality means that both fields match. If you want a total chronological ordering, compare timestamps first and use the value to resolve a tie, provided both fields have a total order. If the goal is simply to sort a batch by timestamp, choosing the timestamp as the key at that call site leaves the type's equality and ordering independent of that one sort. This distinction matters because derived struct ordering compares fields in declaration order.

Syntax and trait contractsOperationTraitAdditiona + bAddEqualitya == bPartialEqOrderinga < bPartialOrdDereference*wrapperDerefIterationfor loopIntoIteratorand IteratorCleanupValuedestructionDropCallcallback()Fn / FnMut /FnOnce
Arithmetic, comparisons, dereferencing, cleanup, iteration, and calls each have their own trait contract.

Deref supports pointer-like access. A wrapper that intentionally behaves like a pointer to its contents can implement it by declaring type Target and providing fn deref(&self) -> &Self::Target. For struct Owned<T>(Box<T>);, an impl<T> std::ops::Deref for Owned<T> can set type Target = T and return self.0.as_ref() from that method. On an instance of that wrapper, *value can access the target, and a borrow of the wrapper can coerce to a borrow of the target where the target reference is expected. Method lookup can also find methods on the target. Use AsRef when you want callers to request the borrowed view explicitly. It lets a label remain a distinct interface with its own methods.

The remaining traits are used by familiar Rust operations as well. Iterator describes sequential access through type Item and fn next(&mut self) -> Option<Self::Item>. A manual implementation fits a type that owns the state required to produce successive items. A for loop obtains its iterator via IntoIterator and then advances it with Iterator::next, stopping at the first None.

Drop lets a resource owner supply fn drop(&mut self) for cleanup when its value is destroyed. A file descriptor owner is a concrete use case because releasing the descriptor requires a close operation. A wrapper around std::fs::File can rely on the file field's existing cleanup. To consume and drop a value explicitly, call std::mem::drop(value). close(2)

Fn, FnMut, and FnOnce describe how callback() may call a function-like value. Fn allows calling through a shared borrow, FnMut through a mutable borrow, and FnOnce allows consuming the callable. A closure that increments a captured counter through a mutable borrow can satisfy FnMut. A closure that moves a captured String out by returning it needs FnOnce. On stable Rust, write a closure or function and use these traits as bounds. Implementing these call traits directly for a custom type requires unstable features.

The next lesson, “Sized and unsized types,” explains why an implementation can return &str or &[u8] from a borrowed conversion even though the amount of text or data can vary at run time.

Key takeaways

  • Implementing From<T> for U supplies Into<U> for T through a blanket implementation.
  • AsRef and AsMut return borrowed views, while TryFrom can report a failed conversion.
  • Display chooses the text for {}, and FromStr defines how parse reads text.
  • An Add implementation defines both the right-hand operand type and the output type.
Reflect
  1. Explain to a colleague, in two sentences: choose between From, TryFrom, AsRef, and AsMut for a given API.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close