what the meaning of "borrowed data escapes outside of closure reference escapes the closure body here" for the following code?

Viewed 25
pub fn restore_string(s: String, indices: Vec<i32>) -> String {
    let mut res_arr_str = vec![""; s.len()]; // 1
    let mut res_arr_char = vec![' '; s.len()]; //2
    let mut res_arr_string = vec!["".to_string(); s.len()]; // 3
    s.char_indices().for_each(move |(index, ch)| {
        res_arr_str[indices[index] as usize] = &ch.to_string();
        res_arr_char[indices[index] as usize] = ch;
        res_arr_string[indices[index] as usize] = ch.to_string();
    });
    res_arr_char.into_iter().collect()
}

i do not understand why 1 is error,but 2 and 3 not,which basic knowlodge i have not understand,which concept

1 Answers

Simplified:

pub fn restore_string(s: String) {
    let mut res_arr_str = vec![""; s.len()];
    s.char_indices().for_each(|(index, ch)| {
        res_arr_str[index] = &ch.to_string();
    });
}

Essentially the problem is that ch.to_string() creates a new String, the lifetime of which only last until the end of the closure body. That is, it will be dropped (destructed, deallocated) when the closure returns. Since the String no longer exists outside the closure, storing a reference to the temporary String is not allowed, or the reference would be a dangling pointer.

Related