Implementing code from walkdir's documentation

Viewed 145

I am new to rust and trying to figure out what I am doing wrong here. From the docs.rs page on walkdir:

The following code recursively iterates over the directory given and prints the path for each entry:

use walkdir::WalkDir;

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

However when I try to run this as a simple program:

use walkdir::WalkDir;
fn main() {
    for entry in WalkDir::new("~/Documents/ExampleDir/") {
        println!("{}", entry?.path().display());
    }
}

I get a 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`

If I remove the ? operator then I get a different compilation error:

error[E0599]: no method named `path` found for enum `std::result::Result<walkdir::DirEntry, walkdir::Error>` in the current scope
 --> src/main.rs:4:30
  |
4 |         println!("{}", entry.path().display());
  |                              ^^^^ method not found in `std::result::Result<walkdir::DirEntry, walkdir::Error>`

What am I doing wrong here? Is this an issue in my code or in the documentation?

1 Answers

The ? is shorthand for a match statement. See The question mark operator.

The question mark operator (?) unwraps valid values or returns erroneous values, propagating them to the calling function. It is a unary postfix operator that can only be applied to the types Result<T, E> and Option.

The (main) function requires a return value of type Result:

use std::error::Error;
use walkdir::WalkDir;

fn main() -> Result<(), Box<dyn Error>> {
    for entry in WalkDir::new("~/Documents/ExampleDir/") {
        println!("{}", entry?.path().display());
    }
    Ok(())
}
Related