2

I tried making a function that returns a string slice. The function takes three arguments:

  1. a the start of the slice
  2. b the end of slice
  3. txt a reference to a string literal
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));
}

The compiler tells me:

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`

compiler response in vscodium on manjaro linux

If I replace the range [a..b] with [2..7] or any other number range it works.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366

1 Answers1

8

Two things to take into consideration, slices use usize instead of u8. Also you would probably want to use &str instead of &String:

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

Playground

Netwave
  • 40,134
  • 6
  • 50
  • 93