rust 59 lines · 9 steps

A validated Email newtype in Rust

Wrap a String in a newtype so an Email can only exist once it has passed validation.

Explained by highlit
1use std::fmt;
2use std::str::FromStr;
3 
4#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5pub struct Email(String);
6 
7#[derive(Debug, thiserror::Error, PartialEq, Eq)]
8pub enum EmailError {
9 #[error("email must not be empty")]
10 Empty,
11 #[error("email must contain exactly one '@'")]
12 MissingAt,
13 #[error("local part must not be empty")]
14 EmptyLocal,
15 #[error("domain must contain a dot and no whitespace")]
16 InvalidDomain,
17}
18 
19impl Email {
20 pub fn parse(raw: &str) -> Result<Self, EmailError> {
21 let trimmed = raw.trim();
22 if trimmed.is_empty() {
23 return Err(EmailError::Empty);
24 }
25 let (local, domain) = match trimmed.split_once('@') {
26 Some(parts) if !parts.1.contains('@') => parts,
27 _ => return Err(EmailError::MissingAt),
28 };
29 if local.is_empty() {
30 return Err(EmailError::EmptyLocal);
31 }
32 if !domain.contains('.') || domain.chars().any(char::is_whitespace) {
33 return Err(EmailError::InvalidDomain);
34 }
35 Ok(Email(trimmed.to_ascii_lowercase()))
36 }
37 
38 pub fn as_str(&self) -> &str {
39 &self.0
40 }
41 
42 pub fn domain(&self) -> &str {
43 self.0.split_once('@').map(|(_, d)| d).unwrap_or_default()
44 }
45}
46 
47impl FromStr for Email {
48 type Err = EmailError;
49 
50 fn from_str(s: &str) -> Result<Self, Self::Err> {
51 Email::parse(s)
52 }
53}
54 
55impl fmt::Display for Email {
56 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57 f.write_str(&self.0)
58 }
59}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A tuple struct with a private field turns 'validated' into a type the compiler enforces everywhere.
  2. 2Returning a typed error enum lets each failure mode carry its own message instead of a generic bool.
  3. 3Implementing FromStr and Display makes a custom type feel native to the standard library.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A validated Email newtype in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code