Parse URL and function chaining in Rust

Viewed 179

I am just starting with Rust programming.

I'm trying to get the last part of a URL, for example, the URL below I want to get the "resource" part:


    http://example.com/some_path1/some_path2/resource

The code I have now is:


    let parsed = Url::parse(url).unwrap();
    let segments = parsed.path_segments().map(|c| c.collect::<Vec<_>>()).unwrap();
    let the_resource = segments.last().unwrap();

There must be a more elegant way to do this.

1) How do I write this more elegantly?

2) Is there a way to use only 1 local variable?

Something like:


    // This of course does not compile because the returns are a mix of Options and Results
    // But the question is, is there a way to chain the function calls (pipes?)

    let the_resource = Url::parse(url)
                           .path_segments()
                           .map(|c| c.collect::<Vec<_>>())
                           .last()
                           .unwrap();

Thanks in advance

1 Answers

Do you think something like this?

extern crate url;

fn get_last(url: &str) -> Result<String, &str> {
    url::Url::parse(url)
        .map_err(|_| "Unable to parse")?
        .path_segments()
        .ok_or("No segments")?
        .last()
        .ok_or("No items")
        .map(String::from)
}

fn main() {
    println!("{:?}", get_last("http://zeljic.com/how/to/parse/url/in/rust"));
}

Playground

Related