Reused vec in loop
โ Rust ๐ 2025-09-23 ๐ค surdeus ๐๏ธ 7fn 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
๐ท๏ธ Rust_feed