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
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 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.