Borrow checker doesn't realize that `clear` drops reference to local variable
The only way to do this is to use transmute
to change the Vec<&'a str>
into a Vec<&'b str>
. transmute
is unsafe and Rust will not raise an error if you forget the call to clear
here. You might want to extend the unsafe
block up to after the call to clear
to make it clear (no pun intended) where the code returns to "safe land".
use std::io::BufRead;
use std::mem;
fn main() {
let stdin = std::io::stdin();
let mut cache = Vec::<&str>::new();
for line in stdin.lock().lines().map(|x| x.unwrap()) {
let cache: &mut Vec<&str> = unsafe { mem::transmute(&mut cache) };
cache.extend(line.split(' '));
println!("{}", cache.join(","));
cache.clear();
}
}
In this case Rust doesn't know what you're trying to do. Unfortunately, .clear()
does not affect how .extend()
is checked.
The cache
is a "vector of strings that live as long as the main function", but in extend()
calls you're appending "strings that live only as long as one loop iteration", so that's a type mismatch. The call to .clear()
doesn't change the types.
Usually such limited-time uses are expressed by making a long-lived opaque object that enables access to its memory by borrowing a temporary object with the right lifetime, like RefCell.borrow()
gives a temporary Ref
object. Implementation of that would be a bit involved and would require unsafe methods for recycling Vec
's internal memory.
In this case an alternative solution could be to avoid any allocations at all (.join()
allocates too) and stream the printing thanks to Peekable
iterator wrapper:
for line in stdin.lock().lines().map(|x| x.unwrap()) {
let mut fields = line.split(' ').peekable();
while let Some(field) = fields.next() {
print!("{}", field);
if fields.peek().is_some() {
print!(",");
}
}
print!("\n");
}
BTW: Francis' answer with transmute
is good too. You can use unsafe
to say you know what you're doing and override the lifetime check.
Itertools has .format()
for the purpose of lazy formatting, which skips allocating a string too.
use std::io::BufRead;
use itertools::Itertools;
fn main() {
let stdin = std::io::stdin();
for line in stdin.lock().lines().map(|x| x.unwrap()) {
println!("{}", line.split(' ').format(","));
}
}
A digression, something like this is a “safe abstraction” in the littlest sense of the solution in another answer here:
fn repurpose<'a, T: ?Sized>(mut v: Vec<&T>) -> Vec<&'a T> {
v.clear();
unsafe {
transmute(v)
}
}