TryFrom Validates Conversions Fallibly

Validate conversions with TryFrom: the associated Error type carries the rejection reason, and TryInto lets callers convert without naming the target type.

RustConfig Management

Code

rustsnippet
30 lines
struct Port(u16);

#[derive(Debug)]
struct PortError(String);

impl TryFrom<u32> for Port {
    type Error = PortError;

    fn try_from(value: u32) -> Result<Self, Self::Error> {
        if value == 0 || value > 65535 {
            return Err(PortError(format!("out of range: {value}")));
        }
        Ok(Port(value as u16))
    }
}

fn main() {
    // TryFrom: a fallible conversion whose error type the implementer defines
    for raw in [80u32, 0, 70_000] {
        match Port::try_from(raw) {
            Ok(p) => println!("port {}", p.0),
            Err(e) => println!("rejected: {e:?}"),
        }
    }

    // TryInto mirrors TryFrom: callers never have to spell out the target type
    let cfg_value: u32 = 443;
    let port: Port = cfg_value.try_into().expect("config port valid");
    println!("bound to port {}", port.0);
}

Inside the snippet

The code’s whole job belongs to the functions try_from and main.

Iteration happens inside for raw in [80u32, 0, 70_000] — everything outside it runs once. Fallible operations return Result, forcing the caller to handle both arms explicitly. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

Points of care

  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Putting it to use

The main signature reads fn try_from(value: u32) -> Result<Self, Self::Error>

The demo output is labeled (port, rejected:, bound to port), so every printed line maps back to its originating operation.

Start the program and main runs try_from one after another.

Core lines

return Err(PortError(format!("out of range: {value}")));
match Port::try_from(raw) {
    Ok(p) => println!("port {}", p.0),
    Err(e) => println!("rejected: {e:?}"),
}
Ok(Port(value as u16))
}

Interactive Tools for This Topic

FAQ

How does the code signal failure?
As data, not exceptions: `Result` makes the caller handle both arms.
What does TryFrom Validates Conversions Fallibly print when run?
Running the file directly is enough — expect labeled output lines such as `port`, `rejected:`, `bound to port`.