In Bash this would be ${0##*/}
.
use std::env;
use std::path::Path;
fn prog() -> String {
let prog = env::args().next().unwrap();
String::from(Path::new(&prog).file_name().unwrap().to_str().unwrap())
}
fn main() {
println!("{}", prog());
}
Is there a better way? (I particularly dislike those numerous unwrap()
s.)
If you don't care about why you can't get the program name, you can handle all the potential errors with a judicious mix of
map
andand_then
. Additionally, return anOption
to indicate possible failure:If you wanted to follow delnan's awesome suggestion to use
std::env::current_exe
(which I just learned about!), replaceenv::args().next()
withenv::current_exe().ok()
.If you do want to know why you can't get the program name (and knowing why is usually the first step to fixing a problem), then check out ker's answer.
You can also get rid of the unwraps and still report all error causes properly (instead of munching them into a "something failed"
None
). You aren't even required to specify the full paths to the conversion methods:Together with the future questionmark operator this can also be written as a single dot call chain:
Of course this has the prerequisite of the
ProgError
type:try it out on the Playground