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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.