0

I'm parsing some text and would like to store a Vec of slices of it.

struct Word<'a> {
    word: &'a str,
    // other_stuff
}
struct Text<'a> {
    text: String,
    words: Vec<Word<'a>>,
    // other_things
}

I don't know how to say the lifetime of word is the same as text. Is something like this possible?

Adamarla
  • 739
  • 9
  • 20
  • As a side note, you're probably better off using a the owned type `String` in `Word` – NebulaFox Mar 20 '20 at 13:14
  • I don't think I understand the question, are you looking for something like this: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=ffd01f8bd7f58504e5ba2417e5cd2b9e ? – Ömer Erden Mar 20 '20 at 13:15
  • @ÖmerErden OP wants the lifetime of text to be the same as words, so to purely express the intent `text: 'a + String`. I don't think that's possible. – NebulaFox Mar 20 '20 at 13:20
  • 1
    Possible in this way: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=65fcc913c454fd927b6cd1a85b267bdd – Ömer Erden Mar 20 '20 at 13:21
  • 1
    @ÖmerErden 's solution and variants are the usual idiomatic ones. An alternative if you want an owned structure is to store byte indices, not references but you must be careful to avoid bugs – Denys Séguret Mar 20 '20 at 13:29
  • @OmerErden more like this: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=94c738fd4a62b9f23a1273d5ab26ede2 – Adamarla Mar 20 '20 at 13:34
  • @Adamarla Word holding the indices instead of the reference. https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f8b181a19e0e3315464a1ceab49527e4 – NebulaFox Mar 20 '20 at 13:42
  • Yes, using indices works, but that is what `The Book` recommends to avoid: https://doc.rust-lang.org/book/ch04-03-slices.html – Adamarla Mar 20 '20 at 13:52
  • 1
    @Adamarla `text` is owned by the function's scope then moved out by returning. This means `text`'s lifetime will always be greater than the function's scope. So that is not possible but i would implement the idea like this : https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7a45af5a80855226a94aeaba68fff428 – Ömer Erden Mar 20 '20 at 13:54
  • @mcarton can you also add this as a duplicate https://stackoverflow.com/questions/28672190/how-do-i-set-the-lifetime-of-a-return-value-as-the-lifetime-of-the-variable-i-mo, IMO this is the real target for dupe. – Ömer Erden Mar 20 '20 at 14:38

0 Answers0