I'm trying to work out how to create a struct that:
- Takes ownership of a String
- Parses the string
- Contains a data structure that contains tokens of the String as slices of the owned string.
- Can return immutable borrows of the String and the tokens with the same lifetime as the struct.
As such, I'm coming up against the fact that I don't really grok lifetimes.
Here's what I've got (this is a toy problem):
struct ParsedString<'input> {
input: String,
tokens: Vec<&'input str>,
}
impl <'input> ParsedString<'input> {
pub fn new(input: &str) -> Self {
let mut ps = ParsedString {
input: input.into(),
tokens: Vec::new(),
};
let len = input.len();
// Pretend to parse the string; really, just save a token.
if len > 4 {
ps.tokens.push(&ps.input[0..3]);
}
// Compilation error here:
// cannot return value referencing local data `ps.input`
ps
}
pub fn input(&self) -> &str {
&self.input
}
pub fn tokens(&self) -> &[&str] {
&self.tokens
}
}
Clearly there's a way to do this.
Ultimately I want to use Cow
so that the tokens can be taken directly from the input
or supplied at parse time.