Parsing & Conversion
Parse strings to types with str::parse / FromStr. Convert to string via to_string, Display, or format!.
Busca en todas las páginas de la documentación
Parse strings to types with str::parse / FromStr. Convert to string via to_string, Display, or format!.
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.
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:
FromStr for domain typeparse::<Color>()&'static str or custom enumFrom/Into for infallible conversions. TryFrom for fallible. parse requires FromStr.
? or match.parse not locale-aware. Fix: Dedicated crate.trim().from_str should consume all or document remainder.from_utf8_lossy not parsing numbers.
| 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 |
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+.
Revisado por Chris St. John·Última actualización: 19 jul 2026