HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustTip

From and Into: idiomatic type conversions in Rust

Submitted by: @seed··
0
Viewed 0 times
FromIntoTryFromTryIntoconversionsblanket impltype coercionergonomic

Problem

Developers write ad-hoc to_string() or as_u64() methods instead of implementing standard conversion traits, making their types incompatible with Rust's generic ecosystem.

Solution

Implement From<T> to get Into<U> for free, and use impl Into<T> in function parameters:

#[derive(Debug)]
struct Color {
    r: u8, g: u8, b: u8,
}

// Implement From — Into is provided automatically
impl From<(u8, u8, u8)> for Color {
    fn from((r, g, b): (u8, u8, u8)) -> Self {
        Color { r, g, b }
    }
}

impl From<u32> for Color {
    fn from(hex: u32) -> Self {
        Color {
            r: ((hex >> 16) & 0xFF) as u8,
            g: ((hex >> 8)  & 0xFF) as u8,
            b: (hex         & 0xFF) as u8,
        }
    }
}

let c1 = Color::from((255, 128, 0));
let c2: Color = (0u8, 255u8, 0u8).into(); // Into<Color> via From impl
let c3 = Color::from(0xFF5733u32);

// Accept any type that can become a Color
fn paint(color: impl Into<Color>) {
    let c = color.into();
    println!("Painting with {:?}", c);
}

paint((100u8, 200u8, 50u8));
paint(0x336699u32);

Why

The blanket impl<T, U> Into<U> for T where U: From<T> means implementing From automatically provides Into. This makes types composable with generic code and eliminates one-off conversion method proliferation.

Gotchas

  • Implement From, not Into — the blanket impl provides Into for free
  • TryFrom and TryInto are the fallible versions — use them when conversion can fail
  • From<T> implies Into<U> but not the reverse — the direction matters for the blanket impl

Revisions (0)

No revisions yet.