I'm still new to Rust. I am trying to make a function that does this:
- Try to read a file in the current working directory's parent directory
- If that fails, try to read a file in the directory two more levels up
- Otherwise return an empty string
- If any error happens (usually the path doesn't exist or the file isn't found), return an empty string as well
I have a solution with .unwrap()
, but now I would like to use the question mark operator for learning purposes. I'm using nightly, so try_blocks would be ok if that helps.
Here's my result so far:
use std::env::current_dir;
use std::fs::read_to_string;
fn main() {
println!("Token: {}", read_token());
}
fn read_token() -> String {
if let Ok(token) = (|| {
let cwd = current_dir()?;
let dir = cwd.parent()?.to_owned();
if let Ok(token) = read_to_string(&dir.join("token")) {
return Ok(token);
}
if let Ok(token) = read_to_string(&dir.parent()?.parent()?.join("token")) {
return Ok(token);
}
return Ok(String::from(""));
})() {
return token;
};
return String::from("");
}
I'm currently getting an error that I don't quite understand:
error[E0282]: type annotations needed
--> src\main.rs:10:19
|
10 | let cwd = current_dir()?;
| ^^^^^^^^^^^^^^ cannot infer type