如何将从env :: current_exe()获得的文件路径转换为字符串或str?

时间:2019-07-05 00:15:49

标签: rust

获取可执行文件的文件路径并在nvs中附加inner_main()后,我尝试在main()中将其转换为字符串:

use std::{env, io, path::PathBuf, process};

fn inner_main() -> io::Result<PathBuf> {
    let exe = env::current_exe()?;
    let dir = exe.parent().expect("Executable must be in some directory");
    let dir = dir.join("nvs");
    Ok(dir)
}

fn main() {
    let path = inner_main() as String;
    println!("The current directory is {:?}", path);
    process::exit(0);
}

它导致错误:

error[E0605]: non-primitive cast: `std::result::Result<std::path::PathBuf, std::io::Error>` as `std::string::String`
  --> src/main.rs:11:16
   |
11 |     let path = inner_main() as String;
   |                ^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait

如何将其转换为String&str

2 个答案:

答案 0 :(得分:1)

快速返工:

use std::path::PathBuf;
use std::process;
use std::env;
use std::io;

fn inner_main() -> io::Result<PathBuf> {
    let mut exe = env::current_exe()?;
    exe.set_file_name("nvs");
    Ok(exe)
}

fn main() {
    match inner_main() {
        Ok(path) => println!("The current directory is {}", path.display()),
        Err(e) => {
            eprintln!("Error determining executable path: {}", e);
            process::exit(1);
        }
    }
}

我认为PathBuf.set_file_name()具有您要针对的语义,并且绝对可靠。

PathBuf.display()返回一个实现Display trait的对象,该对象用于面向用户的格式设置。应当注意,这将有损地转换为UTF-8-对于您正在执行的任何文件系统操作,路径应保持为PathBuf

答案 1 :(得分:1)

如果仅打印路径,则可以使用PathBuf::display

let path = inner_main().unwrap();
println!("The current directory is {}", path.display());

如果需要字符串,可以使用:

let path: String = inner_main().unwrap().to_str().unwrap().to_string();