Description
The Rust std API documentation currently uses the ?
operator in a lot of examples. I think this is likely to be confusing to new Rust developers, who probably haven't encountered it before; it's a powerful shorthand, but it's also confusing and hard to look up.
I think it's a particular problem because error messages surrounding ?
are unclear and hard to debug for someone who's new to Rust, and it's easy to make mistakes when borrowing from the examples in the API docs.
For example, say a new dev wants to write a function that opens a file and writes to it. That developer has probably already clicked through to the documentation for std::result, which most prominently shows using strings as the Err
type for Result
. Searching for writing a file, the user then finds the documentation for std::fs::File, and borrows the code in the example at the top of the page since it does what they wanted it to do. Their resulting code looks something like this:
use std::fs::File;
use std::io::prelude::*;
fn test() -> Result<(), &'static str> {
let mut file = File::create("foo.txt")?;
file.write_all(b"Hello, world!")?;
return Ok(());
}
When trying to build, they get the following errors:
--> test.rs:5:20
|
5 | let mut file = File::create("foo.txt")?;
| ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::convert::From<std::io::Error>` is not implemented for `&str`
|
= note: required by `std::convert::From::from`
error[E0277]: the trait bound `&str: std::convert::From<std::io::Error>` is not satisfied
--> test.rs:6:5
|
6 | file.write_all(b"Hello, world!")?;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::convert::From<std::io::Error>` is not implemented for `&str`
|
= note: required by `std::convert::From::from`
It's not clear at all from this what the problem was, or how copying and pasting these examples caused an issue. As you can probably tell, this example's basically my own experience. 😅 I eventually found out what I was doing wrong, but it does feel a bit like I fell into a trap door that didn't need to be there.