Explicit lifetime required

I have the following code:

use std::collections::HashSet;

pub fn same_word_length<'a>(words: &[&str]) -> HashSet<&'a str> {
    let result: HashSet<&'a str> = HashSet::new();

    for w in words {
        if w.len() == 4 {
            result.insert(w.clone()); <-- lifetime 'a required
        }
    }

    result
}

I cannot change the signature of the function.
What should I do?

You can't implement this with the current signature. That signature accepts strings with any lifetime, including lifetimes shorter than 'a. This means the strings could be destroyed while the returned HashSet is still pointing at them, leading to use-after-free bugs.

If you want to return references to the original strings, they must have the same lifetime as the input references:

pub fn same_word_length<'a>(words: &[&'a str]) -> HashSet<&'a str>

Or you could clone the strings’ contents and return a set of owned Strings:

pub fn same_word_length(words: &[&str]) -> HashSet<String> {
    let mut result = HashSet::new();

    for w in words {
        if w.len() == 4 {
            result.insert(w.to_string());
        }
    }
    
    result
}
3 Likes