skip to content

How do you build a Rust `Email` newtype with `TryFrom<String>` so that no unvalidated string can ever become an `Email`?

level: middleimportance: should knowfreq 55%

answer

  1. the constructor is the only door
  2. private field plus a fallible impl
  3. an associated Error type
  4. From would collide with the blanket impl

basics

~20 s

Keep Email's String field private and implement TryFrom<String> for Email with an associated Error type; try_from validates and returns Result, TryInto comes free, and a From<String> impl must not exist, since rustc rejects the pair with E0119.

solid answer

~40 s

Declare `pub struct Email(String)` with a private field, so code outside the module cannot build one directly. Implement `TryFrom<String> for Email` with `type Error = EmailError` and a `try_from` that checks the text and returns `Ok(Email(s))` or an `Err`. Callers write `Email::try_from(s)` or, through core's blanket impl, `s.try_into()`. Taking `String` lets the success path move the buffer in without reallocating. You cannot add `From<String>` as well: core's `impl<T, U> TryFrom<U> for T where U: Into<T>` would then already provide `TryFrom<String>`, and rustc rejects your impl with E0119. `TryFrom` and `TryInto` have been stable since Rust 1.34 and sit in the prelude from the 2021 edition on.

code

rust · 36 lines
rust
use std::fmt;

#[derive(Debug)]
pub struct Email(String); // private field: the only way in is try_from

#[derive(Debug, PartialEq)]
pub enum EmailError {
    MissingAt,
    EmptyPart,
}

impl TryFrom<String> for Email {
    type Error = EmailError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        let (local, domain) = s.split_once('@').ok_or(EmailError::MissingAt)?;
        if local.is_empty() || domain.is_empty() {
            return Err(EmailError::EmptyPart);
        }
        Ok(Email(s))
    }
}

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

fn main() {
    let ok = Email::try_from(String::from("[email protected]"));
    let bad: Result<Email, _> = String::from("ana.example.org").try_into();
    println!("{ok:?}");
    println!("{bad:?}");
    assert_eq!(bad.unwrap_err(), EmailError::MissingAt);
}

go deeper

for a junior

Recall that TryFrom returns a Result with an associated Error type, and that try_into appears automatically once TryFrom is implemented.

for a middle

Explain the private-field-plus-TryFrom pattern, why the impl takes String, and why a From impl for the same pair is rejected with E0119.

for a senior

Use validated newtypes at trust boundaries so untrusted text is checked once; review for panicking From impls and pub fields that bypass the check.

for a principal

Decide which domain values deserve a validated type at all; each adds an error type and conversions the rest of the codebase must handle.

## From for perfect conversions, TryFrom for the rest `From` is documented as a conversion that **must not fail**. When some inputs are invalid, the standard library's answer is `TryFrom<T>`: ```rust pub trait TryFrom<T>: Sized { type Error; fn try_from(value: T) -> Result<Self, Self::Error>; } ``` It returns a `Result`, and the **associated type** `Error` is chosen by the implementor. The trait puts no bound on `Error`: an enum, a `String`, even `&'static str` all compile. A dedicated error enum is the usual choice because callers can match on it; giving it `Display` and `std::error::Error` impls is covered with custom error types. `TryInto<T>` is the mirror trait, and core provides it through a blanket impl, `impl<T, U> TryInto<U> for T where U: TryFrom<T>`. As with `From` and `Into`, you implement `TryFrom` and get `TryInto` for free. ## The validated-newtype pattern A **newtype** is a one-field tuple struct that gives an existing type a new name and new rules. For `Email` the rule is "contains an `@` with text on both sides". Two pieces make the rule impossible to bypass: 1. **A private field.** `pub struct Email(String)` keeps `.0` private to the defining module, so other modules cannot write `Email(String::from("oops"))`. 2. **A fallible conversion as the only way in.** `impl TryFrom<String> for Email` performs the check once. Every `Email` value in the program has then passed it, and functions that take `Email` need not re-check. Callers can write either spelling: - `Email::try_from(input)` — the target type is named in the call. - `let e: Email = input.try_into()?;` — the target comes from context; the `?` here is ordinary error propagation. The `TryFrom` and `TryInto` traits are in the prelude from the 2021 edition on. Compiled with `--edition 2018`, a bare `300_i32.try_into()` fails with E0599 and the help "items from traits can only be used if the trait is in scope"; on edition 2024 no import is needed. ## Why String rather than &str | Source type | Success path | Failure path | |---|---|---| | `TryFrom<String>` | the buffer moves into `Email`, no new allocation | the `String` is dropped unless the error returns it | | `TryFrom<&str>` | must allocate a `String` copy | nothing to give back | Both impls can coexist, since `TryFrom<String>` and `TryFrom<&str>` are distinct instantiations of the trait; a `&str` version usually delegates with `Email::try_from(s.to_owned())`. Returning the rejected `String` inside the error (`type Error = String`, or an enum variant holding it) hands ownership back to a caller that wants to retry. ## Why From and TryFrom cannot both exist for one pair Core contains a second blanket impl: ```rust impl<T, U> TryFrom<U> for T where U: Into<T> { type Error = Infallible; fn try_from(value: U) -> Result<Self, Self::Error> { Ok(U::into(value)) } } ``` Every infallible conversion is therefore also a fallible one whose error type, `core::convert::Infallible`, has no values. Writing `From<String> for Email` makes `String: Into<Email>`, which makes this blanket impl cover `Email: TryFrom<String>`. A hand-written `TryFrom<String>` then overlaps it, and rustc 1.99 reports **E0119**, conflicting implementations of `TryFrom<String>` for `Email`. The compiler is enforcing the design: a conversion is either infallible or not. ## Choosing the Error type Because the trait leaves `Error` unconstrained, the choice is a design decision: - **An enum of reasons** (`MissingAt`, `EmptyPart`) lets callers match and react, and is the usual choice for a public type. - **The rejected input itself** (`type Error = String`) suits callers that want to correct and retry without cloning. - **`&'static str`** compiles and is handy in a prototype, but callers can only print it. - **`core::convert::Infallible`** appears only on the blanket impl for conversions that cannot fail; you never pick it for a validating type. Whatever you choose, keep it specific to the conversion: one error type per validated newtype keeps messages precise. ## The same split in std's integers The standard library applies the rule to numbers: - Widening conversions that always fit use `From`: `i32::from(7_u16)`. - Narrowing ones use `TryFrom`: `u8::try_from(300_i32)` returns `Err(TryFromIntError)`, while `u8::try_from(200_i32)` returns `Ok(200)`. - The reflexive case `u8::try_from(5_u8)` exists too, with `Error = Infallible`. An `as` cast is the unchecked alternative and is covered with numeric types. ## Mistakes worth catching in review - A `From` impl that calls `panic!` or `unwrap` on invalid input — the `From` docs say not to. - A `pub` field, which lets any module skip validation. - Assuming the trait requires `Error: std::error::Error`; it does not. - A `TryInto` impl written by hand instead of `TryFrom`.

  • Why can't `Email` implement both `From<String>` and `TryFrom<String>`?
    Core's `impl<T, U> TryFrom<U> for T where U: Into<T>` turns every `From` pair into a `TryFrom` pair with `Error = Infallible`. With `From<String>` present, that blanket impl already covers `TryFrom<String> for Email`, so a hand-written one is rejected with E0119, conflicting implementations.
  • What does `u8::try_from(300_i32)` return, and how does that differ from `300_i32 as u8`?
    `try_from` returns `Err(TryFromIntError)` because 300 does not fit in a `u8`. The `as` cast never fails: it truncates to the low 8 bits and yields 44. `TryFrom` makes the out-of-range case visible in the type.
  • Does `TryFrom` require its `Error` type to implement `std::error::Error`?
    No. `TryFrom` declares `type Error;` with no bounds, so `&'static str` or a plain enum compiles. Implementing `Display` and `Error` on it is still good practice when callers will propagate or report it.

A validated newtype works like a building badge issued only at the front desk after an ID check: the desk may refuse, but once someone holds a badge, no inner door checks the ID again.

  • A From impl that panics on invalid input is an acceptable validating constructor.
  • TryFrom's Error type has to implement std::error::Error.
  • A pub inner field is harmless as long as TryFrom checks its input.
  • TryInto must be implemented separately for each TryFrom impl.
  • Email can implement From<String> and TryFrom<String> side by side.

Assumes Rust 1.99 on edition 2024; TryFrom and TryInto are stable since Rust 1.34 and in the prelude from the 2021 edition, so older editions must import them.