Is there a way to avoid cloning when converting a PathBuf to a String?
我需要简单地(并且很危险-为简便起见,不进行错误处理)获得当前的可执行文件名称。我使它工作了,但是我的函数仅将
1 2 3 | fn binary_name() -> String { std::env::current_exe().unwrap().file_name().unwrap().to_str().unwrap().to_string() } |
据我了解,
有什么办法可以避免此
Is there a way to avoid cloning when converting a
PathBuf to aString ?
绝对。但是,那不是您在做什么。您正在通过
如果不提取子集,则可以通过先转换为
1 2 3 4 5 6 7 8 | use std::path::PathBuf; fn exe_name() -> Option<String> { std::env::current_exe() .ok() .map(PathBuf::into_os_string) .and_then(|exe| exe.into_string().ok()) } |
Is there any way to avoid this
&OsStr -> &str -> String -> &str cycle?
否,因为要在方法内部创建