Anagram in rust

I found this solution for choosing the anagram for a specific word :

pub fn anagrams_for<'a>(word: &str, possible_anagrams: &[&'a str]) -> HashSet<&'a str> {
    let mut result = HashSet::new();
    let len = word.len();
    let lower = word.to_lowercase();
    let mut chars: Vec<char> = lower.to_lowercase().chars().collect();
    chars.sort();
    for e in possible_anagrams {
        if len != e.len() || lower == e.to_lowercase() {
            continue;
        }
        let mut test: Vec<char> = e.to_lowercase().chars().collect();
        test.sort();
        if test == chars {
            result.insert(*e);
        }
    }
    result
}

I am confused about the type of possible_anagrams: &[&'a str]
We are borrowing a string already borrowed ?
What does ' stand for before the a ?

Thanks

The &[&'a str] denotes a slice of string slices. The &[...] means it is a slice. The &'a str denotes a string slice.

It is a lifetime. All references in Rust have a lifetime, but the compiler is now smart enough for us to omit it in most cases and it can figure out what we mean to say.
I would suggest you read the chapter on Rust references and lifetimes from the Rust book. It tells you where can you omit the lifetime and where you cannot.

3 Likes

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.