0

I would like to have this kind of struct to save memory allocation:

pub struct MyStruct<'a> {
    corpus: HashSet<String>,
    names: HashMap<&'a String, u8>,
    // we may need some other properties such as addresses: HashMap<&'a String, u8> ...etc from corpus

}

impl MyStruct<'_> {
    pub fn new() -> MyStruct<'static> {
        let mut corpus = HashSet::new();
        corpus.insert("test".to_string());
        corpus.insert("test2".to_string());
        // insert more to the corpus...

        let mut names = HashMap::default();
        names.insert(corpus.get("test").unwrap(), 1);
        MyStruct {
            corpus,
            names,
        }
    }
}

I want to save memory usage of the names property by reusing the corpus that is created from the new method as in the example above. (The corpus and names might have about a few million names). Is it possible? or I must use names: HashMap<String, u8>.

This is the error of course:

102 |           names.insert(corpus.get("test").unwrap(), 1);
    |                        ------------------ `corpus` is borrowed here
103 | /         MyStruct {
104 | |             corpus,
105 | |             names,
106 | |         }
    | |_________^ returns a value referencing data owned by the current function
Kingfisher Phuoc
  • 8,052
  • 9
  • 46
  • 86
  • An alternative that may work for you is using `corpus: Vec` and `name: HashMap`. Checking whether a word is in the corpus will be O(log n) if you sort the vector, which is still fast enough for many use cases. – Sven Marnach Apr 25 '23 at 12:20
  • 1
    If your corpus doesn't change at runtime, you can also simply create a static instance of it, e.g. using `lazy_static`. – Sven Marnach Apr 25 '23 at 12:24
  • @SvenMarnach Thanks. The lazy static may be the way to go. Anyways, I am looking for a better method instead of lazy_static. – Kingfisher Phuoc Apr 25 '23 at 13:12
  • You can also separate the corpus from `MyStruct`, and pass a reference to the corpus when `MyStruct` is constructed. Then you are storing the owned data and the references in different structs. – Sven Marnach Apr 25 '23 at 13:19

0 Answers0