I'm using Rust 0.13, and am rather new to Rust.
I have a struct that would like to own a string input
, but I have code that would like to work with slices of that string, work
.
pub struct Lexer<'a> {
input : Option<String>,
work : &'a str,
...
}
My goal is to pass a string to the struct, have it create its own copy, then to create an initial slice pointing to that string. Ideally, I can now use this slice to manipulate it, as the memory backing the slice won't ever change.
pub fn input(&mut self, input : String) {
self.input = Some(input.clone());
self.work = self.input.unwrap().as_slice();
}
impl<'lex> Iterator<Token> for Lexer<'lex> {
fn next(&mut self) -> Option<Token> {
// ...Do work...
match regex!("\\S").find(self.work) {
Some((0, end)) => {
// Cheap to move the view around
self.work = self.work.slice_from(end);
},
_ => ()
}
// ... Do more work ...
}
}
However, this doesn't work because the lifetime is too short:
error: borrowed value does not live long enough
self.work = self.input.unwrap().as_slice();
^~~~~~~~~~~~~~~~~~~
I'm interpreting this to mean that self.input
could change, invalidating self.work
's view.
Is this a reasonable interpretation?
Is there a way to specify that these fields are tied to each other somehow?
I think if I could specify that Lexer.input
is final this would work, but it doesn't look like Rust has a way to do this.
Edit: sample calling code
let mut lexer = lex::Lexer::new();
lexer.add("[0-9]+", Token::NUM);
lexer.add("\\+", Token::PLUS);
for line in io::stdin().lock().lines() {
match line {
Ok(input) => {
lexer.input(input.as_slice());
lexer.lex();
},
Err(e) => ()
}
}