I'm getting this error, I'm not sure how to solve this.
Scanner implementation:
use crate::token::Token;
pub struct Scanner {
source: String,
tokens: Vec<Token>,
}
impl Scanner {
pub fn new(source: String) -> Scanner {
Scanner {
source,
tokens: vec![],
}
}
pub fn scan_tokens(&mut self) -> &mut Scanner {
// Scan tokens here
self
}
pub fn get_tokens(&self) -> &Vec<Token> {
&self.tokens
}
}
I'm using the above defined struct as follows:
pub fn run(input: String) -> Result<()> {
let mut scanner = Scanner::new(input).scan_tokens();
let tokens = scanner.get_tokens();
Ok(())
}
But the compiler gives the following error:
error[E0716]: temporary value dropped while borrowed
--> src/lib.rs:12:23
|
12 | let mut scanner = Scanner::new(input).scan_tokens();
| ^^^^^^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
13 |
14 | let tokens = scanner.get_tokens();
| -------------------- borrow later used here
|
= note: consider using a `let` binding to create a longer lived value
The error goes away when I do something like this.
pub fn run(input: String) -> Result<()> {
let mut scanner = Scanner::new(input);
scanner.scan_tokens();
let tokens = scanner.get_tokens();
Ok(())
}
But I want to do as written here: https://doc.rust-lang.org/1.0.0/style/ownership/builders.html#non-consuming-builders-(preferred):