pub fn get_attachment_dir() -> PathBuf {
if let Some(dir) = env::var_os("ATTACH_DIR")
&& let Ok(dir) = PathBuf::from(dir).canonicalize()
&& dir.is_dir()
{
dir
} else {
env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
}
}
However, I am not sure that canonicalize is a right operation, because it's expensive. Kotlin has something as also to perform some additional operations in row, but I didn't find an equivalent in Rust.
If "." is sufficient, you're presumably not changing working directories and don't need absolute paths, so you probably don't need canonicalize either.
I don't know kotlin, but looking at the documentation, I think for "wrapped" types, including Iterator, Result or Option, .inspect() should be the closest rust analog to also, but for a generic T, you'll have to use an external crate like tap.
I did also a small benchmark, and the imperative version is a bit faster, about 2%. So I left it in the production code. But I like more the functional version because it's more concise.
Question, if that is allowed... So why the env::current_dir().unwrap_or_else(|_| PathBuf::from(".")) when PathBuf::from(".") would skip a test and a step?
It is a platform specific, for example, if you request current_dir in Linux service, then you will get Err, unless you used WorkingDirectory in the service manifest. So behavior for '.' isn't determined, especially on Windows, because there is no root for the file system. But I do not want to deal with errors, hoping that OS will do something with '.' or simply any file operation will fail, that it's good too.