API Boundaries · 16 min · free lesson

FromStr & Domain Values

Convert raw text into a value that cannot represent an invalid port.

Core idea

A conversion is useful when its output establishes an invariant, not just a new spelling.

Diagram for FromStr & Domain Values: a Rust code example flows to the lesson rule and the key observation.
A validated constructor behind a parsing trait

Understand it

A network port number fits in a u16, but this application's user-selectable port must also be nonzero. A private field and a checked constructor prevent callers from manufacturing an invalid value through ordinary safe code. FromStr then makes the text boundary idiomatic: callers write text.parse::<Port>() and handle the declared error. The conversion is fallible because not every string belongs to the domain.

Keep syntax and domain failures distinct when the caller can act on that difference. In the lab, malformed text and numeric overflow produce invalid; the valid integer zero produces zero. The parser trims surrounding whitespace, but it does not invent a default when the input is absent. Decide separately whether a command-line flag, a configuration file, or a form field is allowed to omit the value.

A From<T> implementation promises an infallible conversion, so do not implement it by panicking for an ordinary invalid input. Use TryFrom for a fallible typed conversion and FromStr for parsing borrowed text. These traits can delegate to the same checked constructor, avoiding divergent rules between your JSON adapter and your command-line adapter. A constructor should not secretly open a socket merely because it validates a port number.

Local compiler profile: standard library only. The typed lab checks zero, whitespace, the largest valid u16, negative text, and overflow. The reading demonstrates the trait implementation; the lab focuses on the checked parsing boundary so its observable contract is straightforward. As an extension, wrap the result in a private-field Port and make every public creation path use the same invariant.

Read the code

use std::str::FromStr;
#[derive(Debug, PartialEq)]
struct Port(u16);
impl FromStr for Port {
    type Err = &'static str;
    fn from_str(
        text: &str,
    ) -> Result<Self, Self::Err> {
        let n = text
            .trim()
            .parse::<u16>()
            .map_err(|_| "invalid")?;
        if n == 0 {
            Err("zero")
        } else {
            Ok(Port(n))
        }
    }
}
fn main() {
    assert_eq!(" 8080 ".parse(), Ok(Port(8080)));
}

A validated constructor behind a parsing trait

Try it

Trim and parse a u16 port. Return zero for the zero-domain error and invalid for malformed or overflowing text; otherwise return the nonzero value. In the Crabrix app, open the compiler lab and complete the supplied function in solution.rs. The reading question is a separate exercise.

What success looks like: The local compiler accepts the changed solution and the separate verification harness finishes all normal and boundary cases. Printing a success message alone does not complete this lab.

Check your understanding

Which trait fits a typed conversion that may reject a value?

Reveal the answer
  1. From, with a panic on invalid values
  2. Copy, because parsing copies bytes
  3. TryFrom, with an error result

TryFrom communicates a fallible conversion in its type. FromStr is the corresponding idiom for parsing text.

Go deeper

Common misconception: A conversion trait should silently choose a default on bad input.

A fallible boundary returns enough information for the caller to choose a policy.

  1. Parse: Trim and parse u16 without discarding errors.
  2. Validate: Reject zero as a separate domain violation.
  3. Encapsulate: Prevent unchecked construction of the domain value.

Transfer challenge: Implement TryFrom<u16> for Port and have FromStr delegate to it. Verify that both paths reject zero.

Connections

  • Compose Optional Fallible Input: map, transpose, and explicit defaults