【发布时间】:2021-10-12 23:33:08
【问题描述】:
我尝试制作一个返回字符串切片的函数。该函数接受三个参数:
-
a切片的开始 -
b切片结束 -
txt对字符串文字的引用
fn main() {
let text = String::from("My name is Ivan");
fn get_slice(a: u8, b: u8, txt: &String) -> &str {
&txt[a..b]
}
println!("{}", get_slice(4, 8, &text));
}
编译器告诉我:
error[E0277]: the type `String` cannot be indexed by `std::ops::Range<u8>`
--> src/main.rs:5:10
|
5 | &txt[a..b]
| ^^^^^^^^^ `String` cannot be indexed by `std::ops::Range<u8>`
|
= help: the trait `Index<std::ops::Range<u8>>` is not implemented for `String`
如果我将[a..b] 范围替换为[2..7] 或任何其他数字范围,它就可以工作。
【问题讨论】: