函数不想使用函数参数返回字符串切片

Iva*_*gin 2 string slice rust

我尝试制作一个返回字符串切片的函数。该函数接受三个参数:

  1. a 切片的开始
  2. b 切片的结尾
  3. 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));
}
Run Code Online (Sandbox Code Playgroud)

编译器告诉我:

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`
Run Code Online (Sandbox Code Playgroud)

manjaro linux 上 vscodium 中的编译器响应

如果我[a..b][2..7]或任何其他数字范围替换范围,它就可以工作。

Net*_*ave 7

需要考虑的两件事,切片使用usize而不是u8. 此外,您可能希望使用&str而不是&String

fn get_slice(a: usize, b: usize, txt: &str) -> &str {
    &txt[a..b]
}
Run Code Online (Sandbox Code Playgroud)

操场