Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function doesn't want to return string slice using function arguments

Tags:

string

slice

rust

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.

like image 972
Ivan Tarnyagin Avatar asked Jul 04 '26 05:07

Ivan Tarnyagin


1 Answers

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

like image 102
Netwave Avatar answered Jul 06 '26 01:07

Netwave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!