如何干净利落地走向bash历史?

问题描述 投票:0回答:1

所以,我一直在研究Rust,这次我有一个简单的任务来获取我的bash历史文件的路径。所以,你想出了env :: var()和env :: home_dir()并想加入它们。现在,它就像是python中的1或2行,可能在C中,我想出了这个可怕的3衬里:

let h_file = env::var("HISTFILE").unwrap_or(OsString::from_string(".bash_history".to_string())).into_string().unwrap_or_else(|_| { panic!("the end is near!!!")});
let h_dir = env::home_dir().unwrap_or_else(|| { panic!("unable to get homedir!") } );
let h_file_p = h_dir.join(h_file);

什么是更好的方式?说实话,我担心,作为初学者,只要使用文档,我想出的就是这个可怕的东西。

编辑:当然重点是第一行是那么长,我知道我可以把所有这些命令放在几行之后,或者使用大量的匹配语句,所有这些都不能真正使这个问题成为一个很好的解决方案一个基本的任务..

rust
1个回答
1
投票

我认为你因为std::old_pathstd::path之间的过渡而受苦,即home_dir()的回归价值。一旦它返回std::path::PathBuf,它将看起来像:

#![feature(os,env,path)]

use std::env;
use std::ffi::OsString;
use std::path::PathBuf;

fn future_home_dir() -> Option<PathBuf> {
    Some(PathBuf::new("/home/user"))
}

fn main() {
    let filename = env::var_os("HISTFILE").unwrap_or(OsString::from_str(".bash_history"));
    let home_dir = future_home_dir().expect("could not determine a home directory");
    let path = home_dir.join(&filename);

    println!("{:?}", path);
}

稳定版本是:

use std::env;
use std::ffi::OsString;

fn main() {
    let filename = env::var_os("HISTFILE").unwrap_or_else(|| OsString::from(".bash_history"));
    let home_dir = env::home_dir().expect("could not determine a home directory");
    let path = home_dir.join(&filename);

    println!("{:?}", path);
}
© www.soinside.com 2019 - 2024. All rights reserved.