skip to content

Why does rustc reject `text.trim().parse()?` with E0277 inside a Rust function returning `Result<u16, io::Error>`, and how do you fix it?

level: middleimportance: must knowfreq 68%

answer

  1. two different error types
  2. the hidden From call
  3. no From<ParseIntError> for io::Error
  4. map_err or a wider error type

basics

~10 s

The ? operator converts the error with From::from, and std has no From<ParseIntError> for io::Error, so rustc reports E0277. Convert explicitly with map_err, or widen the error type, for example to Box<dyn Error>.

solid answer

~40 s

`?` on `Err(e)` returns `Err(From::from(e))`, so the error type of the expression must convert into the function's error type. `fs::read_to_string` fails with `io::Error`, which matches, but `str::parse::<u16>` fails with `ParseIntError`, and std implements no `From<ParseIntError>` for `io::Error`. rustc reports E0277, "`?` couldn't convert the error to `std::io::Error`". You cannot add that impl yourself, because both the trait and the types are foreign (the orphan rule, E0117). The fixes are: convert at the call site with `map_err`, for example `io::Error::new(io::ErrorKind::InvalidData, e)`; change the return type to `Box<dyn Error>`, which every `std::error::Error` type converts into; or return your own error enum that has a `From` impl for each source error.

code

rust · 12 lines
rust
use std::fs;
use std::io;

fn read_port(path: &str) -> Result<u16, io::Error> {
    let text = fs::read_to_string(path)?; // io::Error -> io::Error: fine
    let port: u16 = text.trim().parse()?; // ParseIntError -> io::Error: no From impl
    Ok(port)
}

fn main() {
    println!("{:?}", read_port("app.conf"));
}

go deeper

for a junior

Recall that ? converts the error with From, so the two error types must be connected; when they are not, rustc says it couldn't convert the error.

for a middle

Explain the three fixes, map_err, a wider error type and a typed enum, and why the orphan rule blocks writing From<ParseIntError> for io::Error yourself.

for a senior

Choose the fix by who reads the error: an opaque box is fine at the top of a binary, while a caller that branches on failures needs a typed error with From impls.

for a principal

Treat each E0277 conversion failure as a design signal about error boundaries: decide where errors stay typed and where they are erased, rather than patching each call site.

## The failing code A command-line tool reads its config file and parses a port number from it. The function promises an `io::Error` on failure: ```rust fn read_port(path: &str) -> Result<u16, io::Error> { let text = fs::read_to_string(path)?; // compiles let port: u16 = text.trim().parse()?; // E0277 Ok(port) } ``` rustc 1.99 rejects the second line with **E0277**: "`?` couldn't convert the error to `std::io::Error`", with the label "the trait `From<ParseIntError>` is not implemented for `std::io::Error`" and a note that "the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait". ## Why it happens The `?` operator on a `Result` does not just return the error; it returns `Err(From::from(e))`. Two consequences follow: 1. The type of `e` and the function's error type are allowed to differ, **as long as a `From` impl connects them**. 2. When no such impl exists, the code cannot compile, because the hidden `From::from` call has no implementation to resolve to. In this function: - `fs::read_to_string` returns `Result<String, io::Error>`. The error converts through std's reflexive `From<T> for T`, so the first `?` is fine. - `str::parse::<u16>` returns `Result<u16, ParseIntError>`. `io::Error` has several `From` impls (rustc lists some, such as `From<ErrorKind>` and `From<NulError>`), but none for `ParseIntError`. Note that `?` uses `From` specifically. Implementing only `Into` would not satisfy it, since the conversion is resolved through `From`, and `Into` is derived from `From` rather than the other way round. ## Why you cannot just add the impl The tempting fix is `impl From<ParseIntError> for io::Error` in your own crate. rustc rejects it with **E0117**: "only traits defined in the current crate can be implemented for types defined outside of the crate". `From`, `ParseIntError` and `io::Error` all belong to std, and the orphan rule forbids implementing a foreign trait for a foreign type. The rule itself is covered in the material on coherence; here it simply rules out one fix. ## Three working fixes | Fix | What changes | What the caller gets | |---|---|---| | `map_err` at the call site | one expression | still `io::Error`, with your chosen `ErrorKind` | | Return `Box<dyn Error>` | the signature | an opaque boxed error; matching needs downcasting | | Return your own error enum | the signature plus an enum | a typed error with one variant per source | **Converting at the call site** keeps the signature: ```rust let port: u16 = text .trim() .parse() .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; ``` `map_err` turns `Result<u16, ParseIntError>` into `Result<u16, io::Error>` before `?` sees it, so the conversion `?` performs is the reflexive one. `io::Error::new` accepts any error that can become a `Box<dyn Error + Send + Sync>`, and `ParseIntError` qualifies. **Widening the error type** changes the signature to `Result<u16, Box<dyn Error>>`. std has a blanket impl, `From<E> for Box<dyn Error>` for every `E: Error`, so both `?` uses now convert. It is the shortest fix and a common one in binaries and examples. The cost is that the caller sees an opaque error: to react to "the port was not a number" differently from "the file is missing", it has to downcast. **Returning your own enum** (for example a config error with an `Io` and a `Parse` variant) and writing `From<io::Error>` and `From<ParseIntError>` for it makes both `?` uses work and keeps the failure typed. Designing such an enum and writing those impls are subjects of their own; the point for `?` is that each source error needs **one `From` path** into the function's error type. ## Reading the diagnostic - The error points at the `?` itself, not at `parse`: the failure is in the conversion `?` adds. - The first label, "expected `std::io::Error` because of this", points at the return type, which is the other half of the mismatch. - The `help:` list shows which `From` impls the target type does have, a quick way to see whether some other conversion would fit. - Replacing `?` with `unwrap` also compiles, but that changes behaviour: a malformed port now panics instead of returning an error to the caller. ## Checklist when `?` will not convert 1. Find the error type of the expression (`ParseIntError`) and of the function (`io::Error`). 2. Ask whether a `From` impl links them; rustc's `help:` list answers that. 3. If not, pick the narrowest fix: `map_err` for a one-off, a wider type for application code, a typed enum where callers must tell failures apart.

  • Would implementing `Into<io::Error>` for an error type of your own, instead of `From`, satisfy `?`?
    No. The conversion `?` performs is resolved through `From` on the target type: `Result`'s impl requires `F: From<E>`. std derives `Into` from `From` with a blanket impl, not the reverse, so an `Into` impl alone leaves `?` with nothing to call. Implement `From` on the target type and `Into` comes for free.
  • Why not widen every function's error type to `Box<dyn Error>`?
    It compiles everywhere, but it erases the type. A caller that must treat a missing file differently from a malformed port has to downcast the boxed error, and the compiler no longer lists which failures a function can produce. Plain `Box<dyn Error>` is also neither `Send` nor `Sync`, which matters once errors cross threads. Libraries usually keep typed errors at their boundary.

  • ? converts any error type into any other error type automatically
  • Just write impl From<ParseIntError> for io::Error in your own crate
  • Implementing Into instead of From is enough for ? to convert
  • Swapping ? for unwrap is a harmless way to fix the type mismatch
  • Box<dyn Error> works because ? boxes every error by itself