I'm trying to parse a string and keep it as well as slices to it, but I couldn't convince rust...
struct CategoryAndWord<'a> { word: &'a str, category: &'a str }
struct WordsBank<'a> {
raw_data: String,
words: Vec<CategoryAndWord<'a>>
}
impl WordsBank<'_> {
pub fn from(data: String) -> Self {
let raw_data= data.to_lowercase();
WordsBank{raw_data, words: data.lines().map(WordsBank::line_to_word).collect()}
}
fn line_to_word(l: &str) -> CategoryAndWord {
let mut parts = l.split(" ");
CategoryAndWord{
word: parts.next().expect("Line was empty").trim(),
category: parts.next().expect("Line did not contain ',' followed by category word").trim()
}
}
To my understanding, this code fails because I move raw_data
into the newly created struct, and then lines tries to work on it after the move.
But the underlying String data is still at the same place after the move, so the slices should still be valid.
How do I avoid cloning the underlying data while parsing this string?