0
votes

I have a struct MyStruct<'a> where self.text is of type &'a str

I assumed that this would give me a substring of this str:

let slice: &str  = self.text[i .. self.text.len()];

However I get the following error:

src/lexer.rs:67:28: 67:59 error: mismatched types:
 expected `&str`,
    found `str`
(expected &-ptr,
    found str) [E0308]
src/lexer.rs:67         let slice: &str  = self.text[i .. self.text.len()];

What am I doing wrong?

1
possible duplicate of &str String and lifetime - Chris Morgan

1 Answers

4
votes

self.text[i .. self.text.len()] is of type str; you need to re-borrow the result to get a &str. Also note that you can omit the upper bound on the range. That gets you:

let slice: &str = &self.text[i..];

Edit: To note the why: this is because slicing is just a special case of indexing, which behaves the same way (if you want a borrowed reference to the thing you've indexed, you need to borrow from it). I can't really get into more detail without going into Dynamically Sized Types, which is perhaps best left for a different discussion.