I'd like to create a constructor which stores a String as one field and slices this field in another field. The text is huge and slicing the string it is an expensive operation and it would be better to do it only once.
Here is the problem:
pub struct Article<'a> {
big_text: String,
pub words: Vec<&'a str>,
}
impl<'a> Article<'a> {
pub fn from_text(text: String) -> Article<'a> {
let big_text = text;
let words: Vec<&str> = big_text.split(" ").collect();
return Article { big_text, words };
}
}
It gives compiler errors:
error[E0515]: cannot return value referencing local variable `big_text`
--> src/lib.rs:10:16
|
9 | let words: Vec<&str> = big_text.split(" ").collect();
| ------------------- `big_text` is borrowed here
10 | return Article { big_text, words };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ returns a value referencing data owned by the current function
error[E0505]: cannot move out of `big_text` because it is borrowed
--> src/lib.rs:10:26
|
6 | impl<'a> Article<'a> {
| -- lifetime `'a` defined here
...
9 | let words: Vec<&str> = big_text.split(" ").collect();
| ------------------- borrow of `big_text` occurs here
10 | return Article { big_text, words };
| ----------^^^^^^^^---------
| | |
| | move out of `big_text` occurs here
| returning this value requires that `big_text` is borrowed for `'a`
As I understand it, this happens because when big_text goes out of scope the references (slices) stored in words will become irrelevant.
How do I overcome this issue?