Parsing & Conversion
Parse strings to types with str::parse / FromStr. Convert to string via to_string, Display, or format!.
Recipe
fn parse_port(s: &str) -> Result<u16, std::num::ParseIntError> {
s.trim().parse()
}When to reach for this: Config, CLI args, protocol fields, user input validation.
Working Example
use std::str::FromStr;
#[derive(Debug)]
struct Color { r: u8, g: u8, b: u8 }
impl FromStr for Color {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut parts = s.split(',');
let r: u8 = parts.next().ok_or("r")?.parse().map_err(|_| "r")?;
let g: u8 = parts.next().ok_or("g")?.parse().map_err(|_| "g")?;
let b: u8 = parts.next().ok_or("b")?.parse().map_err(|_| "b")?;
Ok(Color { r, g, b })
}
}
fn main() {
println!("{:?}", "255,128,0".parse::<Color>());
}What this demonstrates:
- Custom
FromStrfor domain type - Turbofish
parse::<Color>() - Error type choice
&'static stror custom enum
Deep Dive
From/Into for infallible conversions. TryFrom for fallible. parse requires FromStr.
Gotchas
- unwrap parse - Panic on bad input. Fix:
?ormatch. - Locale number formats -
parsenot locale-aware. Fix: Dedicated crate. - Trim forgotten - Leading spaces fail int parse. Fix:
trim(). - Partial parse consumption -
from_strshould consume all or document remainder. - Lossy utf8 -
from_utf8_lossynot parsing numbers.
Alternatives
| Alternative | Use When | Don't Use When |
|---|---|---|
serde deserialize | Structured data | Single scalar |
nom / pest | Complex grammars | Simple int parse |
| Regex capture then parse | Semi-structured | Full parser needed |
FAQs
parse inference?
Annotate turbofish or binding type.FromStr Err?
Associated type per type.bool from_str?
"true"/"false" via parse.f64 parse?
PartialEq float issues separate.hex parse?
u32::from_str_radix.Display vs Debug string?
to_string via Display.try_into?
String to Vecclap parse?
clap ValueParser.no_std FromStr?
core for many primitives.test parse errors?
assert!(s.parse::Related
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.