Help with lifetime parameters

Hi,
I am trying to create a struct with its elements pointing to a vector and a hashmap that I intend to use later. I am getting expected named lifetime parameter error while decalring the struct, and I can not seem to figure out this.
This issue seems to be similar to the one explianed in [the book](https://doc.rust-lang.org/stable/book/ch10-03-lifetime-syntax.html) but still I have issues. Could some one please help me where exactly should I declare static or other lifetimes?

use std::collections::HashMap;

fn main(){
    let filenames: Vec<String> = vec!("foo.txt".to_string(), "bar.txt".to_string());
    let mut chrdb: HashMap<String, u64> = HashMap::new();
    chrdb.insert("chr1".to_string(), 10000);
    chrdb.insert("chr2".to_string(), 20000);
    chrdb.insert("chr3".to_string(), 30000);
    
    let ct = Chrtree::new(&filenames, &chrdb);
    
    println!("{:?}", ct);
    
}


struct Chrtree<'a> {
    files: &'a Vec<String>,
    chrlens: &'a HashMap<std::string::String, u64>,
}

impl<'a> Chrtree<'a> {
    fn new(files: &Vec<String>, chrlens: &HashMap<String, u64>) -> &'a Chrtree {
        Chrtree { files, chrlens }
    }
}

(Playground)

You need to expicitly use 'a as lifetime for files and chrlens:

fn new(files: &'a Vec<String>, chrlens: &HashMap<String, u64> -> &a Chrtree {
    Chrtree { files, chrlens }
}

Also prefer using &[T] over &Vec<T>. This allows you to also accept &["a".to_string(), "b".to_string()] in addition to &vec!["a".to_string(), "b".to_string()] as argument.

Hi, Thank you. I have already tried this but does not work for some reason :||

impl<'a> Chrtree<'a> {
    fn new(files: &'a Vec<String>, chrlens: &'a HashMap<String, u64>) -> &'a Chrtree {
        Chrtree { files, chrlens }
    }
}

help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `files` or `chrlens`
help: consider introducing a named lifetime parameter

The &'a Chrtree should be Chrtree<'a>. You are not returning a reference.

1 Like

Ah! Thank you.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.