< 返回版块

rdigua 发表于 2020-04-08 21:37

Tags:rust

感觉写的麻烦 提取PathBuf 成string

fn main() {
    let mut condir = String::new();

    let k = dirs::config_dir();

    println!("The config director is {:?}", k);

    if let Some(z) = k {
        
        println!("The Pathbuf is {:?}", z);

        if let Some(w) = z.to_str() {
            condir.push_str(w);
        } else {
            condir = "".to_string();
        }
    } else {
        condir = "".to_string();
    }

    println!("{}", condir);
}

Cargo.toml

[dependencies]
dirs = "2.0.2"

Print:

The config director is Some("/home/jay/.config") The Pathbuf is "/home/jay/.config" /home/jay/.config

评论区

写评论
leptonyu 2020-04-09 18:36

考虑 ?语法糖

作者 rdigua 2020-04-08 23:52

谢谢 目前感觉 and_then map_or_else ok_or map_or_else ok_or_else map_or unwrap_or_else ... 这些很晕菜

继续学习

对以下内容的回复:

biluohc 2020-04-08 22:17

掌握闭包,Option/Result的一些操作就好了

PS C:\Users\mxo\docs\dirs-try> cat .\src\main.rs
fn main() {
    let cond = dirs::config_dir()
        .and_then(|d| {
            println!("The Pathbuf is {:?}", d);
            d.to_str().map(ToOwned::to_owned)
        })
        .unwrap_or_default();

    println!("Hello, world!: {}", cond);
}
PS C:\Users\mxo\docs\dirs-try> cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target\debug\dirs-try.exe`
The Pathbuf is "C:\\Users\\mxo\\AppData\\Roaming"
Hello, world!: C:\Users\mxo\AppData\Roaming
1 共 3 条评论, 1 页