Rust 选择如何设置主目录

Rust 选择如何设置主目录,rust,rust-cargo,Rust,Rust Cargo,我正在为我的cli程序使用板条箱。如果args中的output dir未通过,我想将home directory设置为默认值。下面是我的代码,请建议我如何实现 Command.rs pub enum Command { #[structopt(name = "init")] Init(InitCmd), } impl Command { /// Wrapper around `StructOpt::from_args` method.

我正在为我的cli程序使用板条箱。如果args中的output dir未通过,我想将home directory设置为默认值。下面是我的代码,请建议我如何实现

Command.rs

pub enum Command {
   
    #[structopt(name = "init")]
    Init(InitCmd), 
}
impl Command {
    /// Wrapper around `StructOpt::from_args` method.
    pub fn from_args() -> Self {
        <Self as StructOpt>::from_args()
    }
}
impl InitCmd{
///运行命令
发布fn执行(&self)->结果{
好(())
}
}

structopt
字段可以采用默认值,但如果没有明确提供该选项,也可以从envvar获取默认值

如果您可以假设在POSIX系统上运行,那么HOME将设置为当前用户的HOME

如果您不能假设POSIX,那么我认为有两种方法:

  • 您还可以将该选项定义为
    选项
    。如果未指定,它将设置为
    None
    ,在使用站点,您可以将
    None
    替换为用户的homedir
  • 定义一个具有所有正确位的自定义类型,以便在未指定时默认为homedir(有关如何执行此操作,请参阅structopt文档,它涉及
    FromStr
    和可选的
    Default
    ToString

无论哪种方式,您都可以使用来获取主目录。

感谢您的重播,我在想,是否可以创建函数来获取主目录,然后在structopt has vaule中传递该函数名?
mod commands;
pub use commands::Command;

fn main(){
    match Command::from_args() {
       Command::Init(cmd) => {
           println!("{:?}", cmd.execute())
       },
   }
 
 }
impl InitCmd {
    /// Run the command
    pub fn execute(&self) -> Result<(), Error> {
        
        Ok(())
    }
}