【问题标题】:Function doesn't want to return string slice using function arguments函数不想使用函数参数返回字符串切片
【发布时间】:2021-10-12 23:33:08
【问题描述】:

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

  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));
}

编译器告诉我:

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] 或任何其他数字范围,它就可以工作。

【问题讨论】:

    标签: string rust slice


    【解决方案1】:

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

    fn get_slice(a: usize, b: usize, txt: &str) -> &str {
        &txt[a..b]
    }
    

    Playground

    【讨论】:

      猜你喜欢
      • 2016-04-26
      • 1970-01-01
      • 2018-03-14
      • 1970-01-01
      • 2014-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多