I'm trying to make a simple log parser as my first project in Rust.
I've made a struct to contain each parsed log line and I'm now making a "parser" struct that should own the BufReader and implement Iterator
to let the user iterate over each parsed line.
As soon as I start implementing Iterator
I'm hitting a snag.
Part of implementing Iterator
is to set an associated type, and I'm not allowed to set the associated type to be LogLine
:
error[E0106]: missing lifetime specifier
--> src/parser.rs:27:17
|
27 | type Item = LogLine;
| ^^^^^^^ expected named lifetime parameter
|
help: consider introducing a named lifetime parameter
|
27 | type Item<'a> = LogLine<'a>;
| ++++ ~~~~~~~~~~~
For more information about this error, try `rustc --explain E0106`.
Why do I have to specify a lifetime parameter for LogLine
? From what I understand, all I've said in the definition of LogLine
is that each string slice field has to live as long as the struct itself.
Why does that make it necessary to provide a named lifetime parameter in this situation, and what do I set it to?
This is my code:
use std::fs::File;
use std::io;
use std::io::BufReader;
pub struct LogParser {
pub bufreader: BufReader<File>,
}
pub struct LogLine<'a> {
line: String,
severity: &'a str,
message: &'a str,
}
impl LogParser {
pub fn new(path: &str) -> io::Result<Self> {
let file = File::open(path)?;
let bufreader = BufReader::new(file);
return Ok(LogParser {
bufreader: bufreader,
});
}
}
impl Iterator for LogParser {
type Item = LogLine;
fn next(&mut self) -> Option<Self::Item> {
// ...
}
}
Unrelated to the question, this is my plan:
- Every parsed line is represented as a
LogLine
struct - The struct has a
line
field that owns the full, original log line - The struct has a bunch of other fields that contains slices of the original string, such as the log severity, the logger name, the date, the message etc.
- Since every other field is a string slice of the
line
field, all the fields should have the same lifetime
I'm hoping this is sound.