I've defined this simple struct for a lexer:

struct Lexer<'a> { source: &'a [u8], pos: usize, } 

For convenience, I've implemented std::ops::Index so that I can write lexer[begin..end] instead of lexer.source[begin..end]:

use std::ops::{Index, Range}; impl<'a> Index<Range<usize>> for Lexer<'a> { type Output = [u8]; fn index(&self, index: Range<usize>) -> &'a [u8] { &self.source[index] } } 

However, now I have the problem that the following function does not compile because there is a lifetime issue:

fn get_bytes_1<'a>(lexer: &Lexer<'a>, range: Range<usize>) -> &'a [u8] { &lexer[range] } 

This is the error:

error[E0621]: explicit lifetime required in the type of `lexer` --> src/tests.rs:472:5 | 472 | &lexer[range] | ^^^^^^^^^^^^^ lifetime `'a` required | help: add explicit lifetime `'a` to the type of `lexer` | 471 | fn get_bytes_1<'a>(lexer: &'a Lexer<'a>, range: Range<usize>) -> &'a [u8] { | ++++++++++ 

Okay, so because the function's return type is &'a [u8] we need to return a reference with lifetime 'a. This is clear. But why does Rust say that &lexer[range] doesn't have lifetime 'a? I mean, 'a refers to the lifetime of Lexer::source, and the return type of index() uses that same lifetime, so I'm confused what the problem is. As the error message indicates, the problem can be solved by explicitly specifying 'a for the lexer argument. But why is this necessary?

What confuses me even more is that the following works:

impl<'a> Lexer<'a> { fn my_index(&self, index: Range<usize>) -> &'a [u8] { &self.source[index] } } fn get_bytes_2<'a>(lexer: &Lexer<'a>, range: Range<usize>) -> &'a [u8] { // This works! lexer.my_index(range) } 

Here I've defined a a custom my_index() function that is -- as far as I can tell -- equivalent to index(). So, what is the difference between these to functions? Why does my_index() work while index() doesn't? I really appreciate any help!

3 posts - 2 participants

Read full topic