From the following code I am getting: borrowed value does not live long enough...
, Can someone help me fix it? I have tried a lot without success
use std::io::{BufRead, stdin, stdout, StdinLock, StdoutLock, BufWriter, Write};
fn main() {
let mut io = IO::new();
let n = io.read::<String>();
io.write(&n);
}
struct IO<'a> {
cin: StdinLock<'a>,
cout: BufWriter<StdoutLock<'a>>,
line: String,
line_buf: std::str::SplitWhitespace<'a>,
}
impl<'a> IO<'a> {
pub fn new() -> Self {
Self { cin: stdin().lock(), cout: BufWriter::new(stdout().lock()), line_buf: "".split_whitespace(), line: String::from("") }
}
pub fn read<T: std::str::FromStr>(&'a mut self) -> T {
let token = match self.line_buf.next() {
Some(value) => value,
None => {
self.cin.read_line(&mut self.line).expect("Error reading line");
self.line_buf = self.line.split_whitespace();
self.line_buf.next().expect("Error reading next token")
}
};
return token.trim().parse().ok().expect("Failed to parse");
}
fn write(&'a mut self, msg: &str) -> () {
write!(&mut self.cout, "{}", msg).ok();
}
}
Error:
error[E0597]: `io` does not live long enough
--> src/bin/competitive_programming_template.rs:5:11
|
5 | let n = io.read::<String>();
| ^^^^^^^^^^^^^^^^^^^ borrowed value does not live long enough
6 | io.write(&n);
7 | }
| -
| |
| `io` dropped here while still borrowed
| borrow might be used here, when `io` is dropped and runs the destructor for type `IO<'_>`