I tried making a function that returns a string slice. The function takes three arguments:
a the start of the sliceb the end of slicetxt a reference to a string literalfn 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`

If I replace the range [a..b] with [2..7] or any other number range it works.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With