'Find all substring indices in string

I am very new to rust, (still working my way through the book) and am re-writing a DNA searching algorithm I wrote in node.js in rust. Each error I've gotten so far I've been able to get through except this one. I am trying to write a function that takes a DNA sequence and a 3-letter flag, and returns all indexes where that flag is found in the input sequence.

fn get_termination_flag_indices (input_sequence: String, flag: String) -> Vec<(usize, &'static str)> {
let flag_indices: Vec<_> = input_sequence.match_indices(&flag).into_iter().collect();

println!("{:?}", flag_indices);
flag_indices
}

I haven't been able to make sense of the error I'm receiving:

returns a value referencing data owned by the current function

I understand from a very high level what it's telling me, but I don't know how to fix it. Honestly I'm just not far enough along to really grasp what's going on here. Any help explaining what's going on under the hood would be extremely helpful.



Solution 1:[1]

Here is how I would solve it (you could make flag a &str to make it even better but it is not required to solve the error):

fn get_termination_flag_indices (input_sequence: &str, flag: String) -> Vec<(usize, &str)> {
    let flag_indices: Vec<_> = input_sequence.match_indices(&flag).into_iter().collect();
    
    println!("{:?}", flag_indices);

    flag_indices
}

Here is what I think caused the error:

Unfortunately, I don't know enough to say for certain but here goes:

When calling match_indices, a reference of input_sequence is created under the hood (match_indices takes a reference to self). Let's give it a lifetime of 'a

Later, the &str that flag_indices collects, has that same lifetime 'a. The problem is that as soon as the function returns with flag_indices, the reference that was created inside the function (with lifetime 'a) is dropped as well. So the flag_indices now contains references that were dropped.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dacite