In Rust, what must a `Meters` type implement for `"12.5m".parse::<Meters>()` to compile, and what does `parse` return?
answer
- parse is generic over its output
- a trait in std::str
- an associated Err type
- turbofish or annotation
basics
~10 sMeters must implement std::str::FromStr, choosing an associated Err type and writing from_str(&str) returning Result<Self, Self::Err>. str::parse::<F>() just calls F::from_str, so it returns Result<Meters, Meters's Err type>.
solid answer
~30 s`str::parse` is declared as `pub fn parse<F: FromStr>(&self) -> Result<F, F::Err>` and its body is `FromStr::from_str(self)`. So `Meters` needs `impl FromStr for Meters` with `type Err` and `fn from_str(s: &str) -> Result<Self, Self::Err>`; the result is `Result<Meters, Meters's Err>`. The target type must be known, from the turbofish `parse::<Meters>()` or an annotation such as `let m: Meters = s.parse()?`; without one rustc reports E0284, "type annotations needed". `TryFrom<&str>` does not enable `parse`: rustc still says `FromStr` is not implemented (E0277). `FromStr` has no lifetime parameter, so it can only produce types that own their data.
code
rust · 22 linesuse std::num::ParseFloatError;
use std::str::FromStr;
#[derive(Debug, PartialEq)]
struct Meters(f64);
impl FromStr for Meters {
type Err = ParseFloatError;
// Accepts "12.5" or "12.5m"
fn from_str(s: &str) -> Result<Self, Self::Err> {
let number = s.trim().trim_end_matches('m');
number.parse::<f64>().map(Meters)
}
}
fn main() {
let a: Meters = "12.5m".parse().unwrap();
let b = "3".parse::<Meters>();
let c = Meters::from_str("tall");
println!("{a:?} {b:?} {}", c.is_err());
}go deeper
Recall that parse needs the target type to implement FromStr, returns a Result, and needs a turbofish or annotation to know the target.
Explain how parse delegates to from_str, how to choose the Err type, and why TryFrom<&str> does not enable parse.
Design parsing for untrusted input: precise error types callers can match on, no unwrap in from_str, and a format that round-trips with Display when machines read it.
Agree on one text format per domain type across services and tools, so FromStr and Display stay a documented, stable contract.
## FromStr and str::parse Turning text into a typed value is so common that the standard library gives it a dedicated trait, `std::str::FromStr` (defined in `core::str`): ```rust pub trait FromStr: Sized { type Err; fn from_str(s: &str) -> Result<Self, Self::Err>; } ``` - `from_str` takes a borrowed `&str` and returns a `Result`, because almost any text can be malformed. - `Err` is an **associated type**: each implementor picks its own error, such as `ParseIntError` for integers or `ParseFloatError` for floats. Most code never calls `from_str` by name. It calls `str::parse`, declared as `pub fn parse<F: FromStr>(&self) -> Result<F, F::Err>`, whose whole body is `FromStr::from_str(self)`. `parse` itself adds no logic: whether it panics, what it accepts and which error it returns are all decided by the type's `FromStr` impl. ## Implementing it for Meters For a units type that accepts `"12.5"` or `"12.5m"`: 1. Write `impl FromStr for Meters`. 2. Pick `type Err`. Reusing `ParseFloatError` is fine when every failure is a number failure; a custom enum is better when there are several failure reasons. 3. In `from_str`, strip the unit suffix and delegate the number to `f64`'s own `FromStr`: `number.parse::<f64>().map(Meters)`. `"12.5m".parse::<Meters>()` then returns `Ok(Meters(12.5))`, and `"tall".parse::<Meters>()` returns an `Err` holding a `ParseFloatError`. Nothing panics unless the caller chooses `unwrap`. ## Telling parse the target type `parse` is generic over its output, so the compiler must know `F`: - **Turbofish**: `"3".parse::<Meters>()` names the type in the call. The `parse` documentation calls this out as one of the few common places the `::<>` syntax appears. - **Annotation**: `let m: Meters = s.parse()?;` lets inference carry the type from the binding. - **Context**: passing the result to a function that takes `Meters` works too. With none of these — `let n = "42".parse().unwrap();` followed by `println!("{n}")` — rustc 1.99 reports **E0284**, "type annotations needed", with the note "cannot satisfy `<_ as FromStr>::Err == _`". Rust does not default the target to an integer type. ## FromStr compared with TryFrom<&str> | | `FromStr` | `TryFrom<&str>` | |---|---|---| | Enables `str::parse` | yes | no | | Can produce a type that borrows from the input | no | yes, `impl<'a> TryFrom<&'a str> for Key<'a>` | | Error type name | `Err` | `Error` | | Gets a blanket mirror trait | no | `TryInto` for `&str` | The first row trips people up: a type that implements only `TryFrom<&str>` still fails `"12.5".parse::<Meters>()` with **E0277**, "the trait bound `Meters: FromStr` is not satisfied". Implement `FromStr` for anything that should work with `parse`; add `TryFrom<&str>` only if callers also want the conversion-trait spelling. ## What std's own FromStr impls accept Knowing a few built-in impls prevents surprises when you delegate to them, as the `Meters` impl delegates to `f64`: - **Integers** use `ParseIntError`. They accept an optional leading `+` or `-` sign but reject surrounding whitespace, so `" 42".parse::<i32>()` is an `Err`; trim first. - **Floats** use `ParseFloatError` and also accept special spellings such as `"inf"` and `"NaN"`, which a units type may want to reject explicitly. - **`bool`** accepts exactly `"true"` and `"false"`; `"True"` is an error (`ParseBoolError`). - **`IpAddr`** and the socket-address types use `AddrParseError`. - **`String`** implements `FromStr` with `Err = Infallible`, because every `&str` is already valid text. ## Limits written into the trait - **No lifetime parameter.** The `FromStr` docs state that you can parse an `i32` but not an `&i32`, and a struct containing an `i32` but not one containing an `&i32`. A zero-copy parser that returns views into its input needs a plain function or `TryFrom<&'a str>`. - **No round-trip guarantee.** The docs warn that a type's `FromStr` input format need not accept what its `Display` impl prints. If `Display` output is meant to be machine-parseable, accepting the same format in `FromStr` and documenting it avoids surprising users. ## Mistakes worth catching in review - Expecting `parse` to panic on bad input; it returns `Err`. - Implementing `TryFrom<&str>` and wondering why `parse` does not compile. - Leaving out the turbofish where nothing else names the type. - Trying to make `from_str` return a struct that borrows from `s`.
- Can `FromStr::from_str` return a struct that borrows from its `&str` argument?No. `FromStr` has no lifetime parameter linking the output to the input, so the result must own its data; the std docs give `i32` versus `&i32` as the example. A borrowing view needs a function with an explicit lifetime or `impl<'a> TryFrom<&'a str> for View<'a>`.
- If `Meters` implements `TryFrom<&str>`, does `"1.5".parse::<Meters>()` work?No. `parse` is bounded on `F: FromStr` only, so rustc 1.99 reports E0277, the trait bound `Meters: FromStr` is not satisfied. Implement `FromStr`; a `TryFrom<&str>` impl can delegate to it.
- str::parse works for any type that implements TryFrom<&str>.
- parse panics when the string is not valid for the target type.
- FromStr can return a struct that borrows slices of the input &str.
- Without an annotation, parse defaults its target to i32.
- A type's FromStr must accept exactly the text its Display prints.