0

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
wirrbel
  • 3,173
  • 3
  • 26
  • 49
  • possible duplicate of [&str String and lifetime](http://stackoverflow.com/questions/28999226/str-string-and-lifetime) – Chris Morgan Mar 12 '15 at 08:03

1 Answers1

4

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.

DK.
  • 55,277
  • 5
  • 189
  • 162