Error with function return value

⚓ Rust    📅 2025-08-17    👤 surdeus    👁️ 8      

surdeus

The following code does not compile and gives the error: error[E0515]: cannot return value referencing local variable 'map'

use std::collections::HashMap;

#[derive(Debug)]
struct Ctx<'a> {
    map: HashMap<u32, String>,
    vec: Vec<&'a str>,
}

fn mk_ctx<'a>() -> Ctx<'a> {
    let map: HashMap<u32, String> = HashMap::from([(0, "foo".into())]);
    let vec: Vec<&str> = mk_vec(&map);

    Ctx { map, vec }
}

fn mk_vec(map: &HashMap<u32, String>) -> Vec<&str> {
    todo!()
}

fn main() {
    let res = mk_ctx();
    println!("{res:?}")
}

Sandbox

As far as I understand due to map being a parameter to mk_vec and by applying lifetime elision rules, the &str in vec will have the same lifetime as map. At the end of mk_ctx map is moved to ctx.map. I would assume that vec can be moved to ctx.vec as well.

What is the issue here and how can the code be fixed?

10 posts - 5 participants

Read full topic

🏷️ Rust_feed