Reused vec in loop

โš“ Rust    ๐Ÿ“… 2025-09-23    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 7      

surdeus

Warning

This post was published 38 days ago. The information described in this article may have changed.

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Reused vec in loop
fn test() {
    let mut vec = vec![];
    for i in 0..1000000000 {
        let s = format!("hello world {}", i);
        vec.push(s.as_str());
        vec.iter().for_each(|s| println!("do something: {}", s));
        vec.clear();
    }
}

In a situation like this, Vec runs into a lifetime issue, showing the error s does not live long enough. However, by looking at the code we can tell that s will be removed from the Vec after the loop ends, so there is actually no problem. In such scenarios, how can we reuse the Vec and resolve the lifetime issueโ€”either in a safe or unsafe way?

5 posts - 5 participants

Read full topic

๐Ÿท๏ธ Rust_feed