Fork me on GitHub
#other-languages
<
2019-12-03
>
borkdude12:12:29

how do I make this compile in Rust?

use walkdir::WalkDir;

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

fn main() {
    print();
}

borkdude12:12:43

error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
 --> src/main.rs:5:24
  |
5 |         println!("{}", entry?.path().display());
  |                        ^^^^^^ cannot use the `?` operator in a function that returns `()
`

borkdude12:12:59

I get the error, but I don't know how to fix it yet

borkdude12:12:56

This worked!

use walkdir::WalkDir;
use std::io;

fn print() -> Result<(), io::Error>  {
    for entry in WalkDir::new(".") {
        println!("{}", entry?.path().display());
    };
    return Ok(());
}

fn main() {
    let _ = print();
}

aw_yeah 4
gklijs15:12:42

It a bit rusty, but I think instead use entry.expect("empty entry").path.display() might be better, Don't make much sense to return an error and do nothing with it, but it probably will not be called anyway.

borkdude15:12:09

@gklijs This came directly from a Rust readme

gklijs15:12:16

Well, it does work, but seems weird to me.

gklijs16:12:02

Yes, you should probable want to do something with the error in main trough, and not just ignore the result.

borkdude16:12:12

first silence the type checker .. oh that's not the point is it? 😉