Returning iterators and combining them

Viewed 54

New to Rust and I have the following code for parsing a query in Actix that constructs a bunch of keys to query Redis:

#[derive(Debug, Deserialize)]
struct RouteRequest {
    proto: String,
    ids: Option<String>,
    aliases: Option<String>
}

fn get_redis_keys_from_ids(ids: Option<&String>) -> Vec<String> {
    match ids {
        None => vec!{},
        Some(s) => s.split(",").map(|s| "id:".to_owned() + s).collect()
    }
}

fn get_redis_keys_from_aliases(aliases: Option<&String>) -> Vec<String> {
    match aliases {
        None => vec!{},
        Some(s) => s.split(",").map(|s| "aid:".to_owned() + s).collect()
    }
}

fn get_redis_keys(req: web::Form<RouteRequest>) -> Vec<String> {
    let ids = get_redis_keys_from_ids(req.ids.as_ref());
    let aliases = get_redis_keys_from_aliases(req.aliases.as_ref());

    ids.into_iter().chain(aliases.into_iter()).collect()
}

Basically, if I have the following data:

RouteRequest {
  ids: "foo,bar"
  aliases: "baz,crux"
}

Then the vector returned by get_redis_keys() should be:

{"id:foo", "id:bar", "aid:baz", "aid:crux"}

What would be the cleanest and most efficient way of writing this code? Currently, I do this mapping of Option<String> to Option<&String> not sure if that's necessary, since I could just take ownership of the Option? I'm also returning Vecs from the helper functions, which causes unnecessary heap allocations.

In other words, how do I write this code in a better way avoiding unnecessary allocations? Trying to learn some Rust here.

0 Answers
Related