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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A tuple struct with a private field turns 'validated' into a type the compiler enforces everywhere.
- 2Returning a typed error enum lets each failure mode carry its own message instead of a generic bool.
- 3Implementing FromStr and Display makes a custom type feel native to the standard library.
Related explainers
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
rust
use std::cmp::Ordering; pub struct PrefixIndex { entries: Vec<String>,
Prefix search with binary partitioning in Rust
binary-search
sorting
case-insensitive
Intermediate
7 steps
php
<?php namespace App\Http\Controllers;
Streaming a filtered CSV export in Laravel
streaming
csv-export
query-builder
Intermediate
9 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
ruby
class Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-validated-email-newtype-in-rust-explained-rust-efc1/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.