有时,例如,当读取某些配置文件时,您读取了用户输入的文件路径而无需通过外壳程序(例如,获得~/test)。
正如Option 2下面不写在用户主目录下的测试文件,我想知道,如果有什么比更地道Option 1。
use std::env::var;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
fn write_to(path: &Path) {
let mut f = File::create(path).unwrap();
f.write_all("Hi".as_bytes()).unwrap();
}
fn main() {
// Option 1
let from_env = format!("{}/test", var("HOME").unwrap());
let with_var = Path::new(&from_env);
// Create $HOME/test
write_to(with_var);
// Option 2
let with_tilde = Path::new("~/test");
// Create the test file in current directory, provided a directory ./~ exists
write_to(with_tilde);
}
Run Code Online (Sandbox Code Playgroud)
注意:unwrap()此处用于使示例简短。生产代码中应该有一些错误处理。