0

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?

feature_engineer
  • 1,088
  • 8
  • 16
  • You can't store them in the same struct, due to Rust default movability. You need to store data and parsed object in two different structs, so that the lifetime of the parsed data that references the original data isn't a self-reference. Self-referential lifetimes don't work in Rust. – Finomnis Jan 10 '23 at 14:21

0 Answers0