简体   繁体   English

索引&str时出现“错误:类型不匹配”

[英]“error: mismatched types” when indexing a &str

I have a struct MyStruct<'a> where self.text is of type &'a str 我有一个struct MyStruct<'a> ,其中self.text&'a str类型

I assumed that this would give me a substring of this str: 我以为这会给我这个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 ; self.text[i .. self.text.len()]的类型为str you need to re-borrow the result to get a &str . 您需要重新借入结果以获得&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. 如果不进入“动态大小类型”,我真的无法进一步详细介绍,这也许最好留给其他讨论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM