Critique of code

A small beginner exercise. Did I miss any idioms? Did I get the lifetime correct?

use std::env;

fn basename<'a>(path: &'a str, suff: &str) -> &'a str {
    let ps = match path.rfind('/') {
        None => path,
        Some(ns) => &path[ns+1..]
    };
    let mut ne: usize = ps.len();
    if ps.ends_with(suff) {
        ne -= suff.len();
    }
    &ps[..ne]
}

fn main() {
    let p = env::args().next().unwrap();
    let prog = basename(&p, ".foop");
    println!("{}", prog);
}

Please add a code block by putting triple ` character before and after the code. https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#code

Just to expand on dpc's tip for using the forum, to format code you can do:

```rust
Code goes here
⁣```

For example, your code is easy to read like this:

use std::env;

fn basename<'a>(path: &'a str, suff: &str) -> &'a str {
    let ps = match path.rfind('/') {
        None => path,
        Some(ns) => &path[ns + 1..],
    };
    let mut ne: usize = ps.len();
    if ps.ends_with(suff) {
        ne -= suff.len();
    }
    &ps[..ne]
}

fn main() {
    let p = env::args().next().unwrap();
    let prog = basename(&p, ".foop");
    println!("{}", prog);
}

Looks good!

One minor note, Option<T> has a lot of useful methods, you can look into using them instead of a match to improve readability, for example, instead of using

let ps = match path.rfind('/') {
    None => path,
    Some(ns) => &path[ns + 1..],
};

You can use Option::map_or

let path = path.rfind('/').map_or(path, |ns| &path[ns+1..]);
4 Likes

Got it. Thanks.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.