I am working on a small lexer in Rust. I had the idea of putting the lexing phase into the implementation of the Iterator
trait.
struct Lexer {
text: String
}
impl Iterator for Lexer {
...
fn next(&mut self) -> Option<LexItem>{
....
// slicing issue
self.text = self.text[i .. self.text.len()]
}
}
I have not quite grokked lifetime management here completely. I would be fine by defining the struct with a lifetime for the text
attribute which would (probably) make the subslicing more easy. Yet I fail to incorporate such a lifetime in my code. On the other hand, I have a hard time converting the slice self.text[i .. .....]
into a String
again (dunno if that is possible).
What I tried:
I tried the following modification:
struct Lexer<'a> {
text: &'a str
}
impl<'a> Iterator for Lexer<'a> {
...
fn next(&'a mut self) -> Option<LexItem>{
....
// slicing issue
self.text = self.text[i .. self.text.len()]
}
}
I get the error:
src/lexer.rs:64:5: 81:6 error: method `next` has an incompatible type for trait: expected bound lifetime parameter , found concrete lifetime [E0053]
the other implementation I tried
impl<'a> Iterator for Lexer<'a> {
...
fn next<'b>(&'b mut self) -> Option<LexItem>{
....
// slicing issue
self.text = self.text[i .. self.text.len()]
}
}
src/lexer.rs:66:21: 66:52 error: mismatched types: expected `&'a str`, found `str` (expected &-ptr, found str) [E0308] src/lexer.rs:66 self.text = self.text[i .. self.text.len()]; ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I figure that something like this should work, as I would work with subslices only.