Export slice from a string inside a block. error[E0597]: `line` does not live long enough
⚓ Rust 📅 2026-02-03 👤 surdeus 👁️ 10Hi, by curiosity, we can't export a copy of a substring from a string defined inside a block. We get an error that explain that string doesn't live outside the block, but we just want a copy part of that string.
How could we export a copy of a slice of local/inside string to make it available outside the block ?
I already found workarounds.correction by using the heap (by string, not &str), or by defining variables outside and before the block.
// Test : export slice from a string inside a block
fn main () {
let mut version : & str = "0.0.0"; // default value
// let mut line = String::new(); // it works if "line" is already existant outside the block
for _i in [1..=2] { // some loop because of treatment
// build local(inside the block) string "line" from some function or whatever. Here it is just a given example.
let line = String::from(":v 1.2.3\r"); // or ":v1.2.3\r" (without space)
// line = String::from(":v 1.2.3\r"); // or ":v1.2.3\r" (without space) <-- it works (because defined outside and will still exists after the block)
// exctract "version" from "line" : = line(2..)
// ======= ERROR HERE ==========
// error[E0597]: `line` does not live long enough
// I would like to copy the part "1.2.3" from ":v 1.2.3"
version = line.get(2..).unwrap_or("").trim();
}; // line has ended here
println!("{}", version);
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0597]: `line` does not live long enough
--> src/main.rs:15:19
|
8 | let line = String::from(":v 1.2.3\r"); // or ":v1.2.3\r" (without space)
| ---- binding `line` declared here
...
15 | version = line.get(2..).unwrap_or("").trim();
| ^^^^ borrowed value does not live long enough
16 |
17 | }; // line has ended here
| - `line` dropped here while still borrowed
18 |
19 | println!("{}", version);
| ------- borrow later used here
For more information about this error, try `rustc --explain E0597`.
error: could not compile `playground` (bin "playground") due to 1 previous error
3 posts - 3 participants
🏷️ Rust_feed