简体   繁体   中英

How to convert a list of &str into a list of static &str?

So I'm new to Rust and working on a string exercise and have the following:

pub fn anagrams_for<'a>(word: &str, possible_anagrams: &[&str]) -> HashSet<&'a str> {
    let mut my_hashset: HashSet<&'a str> = HashSet::new();
    for anagram in possible_anagrams {
        if is_anagram(word, anagram) {
            my_hashset.insert(anagram);
        }
    }
    return hs;
}

But I get the following error:

explicit lifetime required in the type of `possible_anagrams`: lifetime `'a` required

How do I add this in Rust?

EDIT: One other question - how would I add this without modifying the function parameters passed in? Do I need a new mutable variable that clones possible_anagrams? I'm asking because I think the kata won't let me have control over what is passed in initially. But I will have control over what I can do to the parameter once I'm inside the function.

You can specify lifetime for slice's &str s

pub fn anagrams_for<'a>(word: &str, possible_anagrams: &[&'a str]) -> HashSet<&'a str> {
    let mut my_hashset: HashSet<&'a str> = HashSet::new();
    for anagram in possible_anagrams {
        if is_anagram(word, anagram) {
            my_hashset.insert(anagram);
        }
    }
    return my_hashset;
}

rust.playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM