Reputation: 13
I am newbie on rust and trying an example to read dir on Win10 from:
https://rust-lang-nursery.github.io/rust-cookbook/file/dir.html
However the code cannot compile due to return result is expecting 2 type arguments:
std::io::Error
std::time::SystemTimeError
use std::fs;
fn main() -> Result<()> {
let current_dir = "C:/temp/";
println!(
"Entries modified in the last 24 hours in {:?}:",
current_dir
);
for entry in fs::read_dir(current_dir)? {
let entry = entry?;
let path = entry.path();
let metadata = fs::metadata(&path)?;
let last_modified = metadata.modified()?.elapsed()?.as_secs();
if last_modified < 24 * 3600 && metadata.is_file() {
println!(
"Last modified: {:?} seconds, is read only: {:?}, size: {:?} bytes, filename: {:?}",
last_modified,
metadata.permissions().readonly(),
metadata.len(),
path.file_name().ok_or("No filename")?
);
}
}
Ok(())
}
Here is the playground link:
Upvotes: 1
Views: 271
Reputation: 42217
If you click the "expand" button in the top-right corner of the snippet, you'll see that there are bits which are hidden by default:
use error_chain::error_chain;
use std::{env, fs};
error_chain! {
foreign_links {
Io(std::io::Error);
SystemTimeError(std::time::SystemTimeError);
}
}
fn main() -> Result<()> {
// ...
those bits turn out to be quite relevant because by default error_chain! automatically generates a Result
alias such that you only need to specify the "Ok" parameter and the other is the generated error type (similar to std::io::Result
, which is a typedef for std::result::Result<T, std::io::Error>
).
So you need to either expand the snippet before copying it (error_chain
is available on the playground) or hand-roll the Result
alias... and possibly error type though here you could just define type Result<T> = Result<T, Box<dyn std::error::Error>>
and it should work.
This behaviour (of the cookbook) is explained in the about page's a note about error handling section though I can't say I'm fond of it, given cookbooks are generally not things you read start-to-end.
Upvotes: 2