Try New Fallible Constructor Validates

try_new returns Result<Self, String> so invalid port numbers become construction-time errors instead of broken values circulating in memory.

RustData Integrity

Code

rustsnippet
30 lines
#[derive(Debug)]
struct Port {
    value: u16,
}

impl Port {
    // Fallible constructor: invalid input becomes an Err, never a broken value
    fn try_new(raw: i64) -> Result<Self, String> {
        if raw < 0 {
            return Err(format!("port {raw} is negative"));
        }
        if raw > u16::MAX as i64 {
            return Err(format!("port {raw} exceeds {}", u16::MAX));
        }
        Ok(Self { value: raw as u16 })
    }

    fn value(&self) -> u16 {
        self.value
    }
}

fn main() {
    for raw in [80, 0, -1, 70_000] {
        match Port::try_new(raw) {
            Ok(port) => println!("ok: {raw} -> {}", port.value()),
            Err(reason) => println!("rejected {raw}: {reason}"),
        }
    }
}

The code at a glance — Try New Fallible Constructor Validates

What actually executes are the functionss try_new, value and main — everything else is wiring.

One loop does the cycling here: for raw in [80, 0, -1, 70_000]. Fallible operations return Result, forcing the caller to handle both arms explicitly. Pattern matching via match forces each shape of the value to be handled.

Points of care

  • Nothing gets pulled from a registry — the platform ships every API used here.
  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Applying it

Signature: fn try_new(raw: i64) -> Result<Self, String>

The demo output is labeled (ok:, rejected); each label names the call that printed it.

The demo flow inside main is try_new and value — run the file to see it end to end.

Statements that matter

return Err(format!("port {raw} exceeds {}", u16::MAX));
return Err(format!("port {raw} is negative"));
Ok(Self { value: raw as u16 })
}

Interactive Tools for This Topic

FAQ

Is there exception handling?
As `Result` values — each fallible call returns one, and the caller matches or propagates it.
What does Try New Fallible Constructor Validates print when run?
No setup needed: run the file and look for labeled lines like `ok:`, `rejected` in the output.