小编leo*_*ukw的帖子

惯用地在Rust路径中扩展波浪号

有时,例如,当读取某些配置文件时,您读取了用户输入的文件路径而无需通过外壳程序(例如,获得~/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()此处用于使示例简短。生产代码中应该有一些错误处理。

directory path home-directory rust

2
推荐指数
1
解决办法
684
查看次数

标签 统计

directory ×1

home-directory ×1

path ×1

rust ×1