BurntSushi / walkdir

Rust library for walking directories recursively.
The Unlicense
1.21k stars 106 forks source link

Example code in documentation fails to compile #148

Closed PeetoomHeida closed 3 years ago

PeetoomHeida commented 3 years ago

Trying to run code from the documentation fails to compile. The following code block comes from docs.rs:

use walkdir::WalkDir;

for entry in WalkDir::new("foo") {
    println!("{}", entry?.path().display());
}

Putting it into a simple program:

use walkdir::WalkDir;

fn main () {
    for entry in WalkDir::new("foo") {
        println!("{}", entry?.path().display());
    }
}

returns the following compilation error

error[E0277]:` the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `Try`)
 --> src/main.rs:4:24
  |
2 | / fn main() {
3 | |     for entry in WalkDir::new("foo") {
4 | |         println!("{}", entry?.path().display());
  | |                        ^^^^^^ cannot use the `?` operator in a function that returns `()`
5 | |     }
6 | | }
  | |_- this function should return `Result` or `Option` to accept `?`
  |
  = help: the trait `Try` is not implemented for `()`
  = note: required by `from_error`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.
error: could not compile `walkdir_test`

To learn more, run the command again with --verbose.
BurntSushi commented 3 years ago

The ? operator in this case requires the code to be used in a function that returns a Result.

PeetoomHeida commented 3 years ago

Removing the ? operator will still cause a compilation error due to:

no method named `path` found for enum `std::result::Result<walkdir::DirEntry, walkdir::Error>` in the current scope

method not found in `std::result::Result<walkdir::DirEntry, walkdir::Error>`rustc(E0599)
main.rs(4, 30): method not found in `std::result::Result<walkdir::DirEntry, walkdir::Error>`

The larger issue is that the code in the documentation will not run "out of the box" so to speak.