Avatar ·

How to get a slice from Vec<T> in Rust: complete guide

Hi everyone! I started learning Rust and encountered a problem when working with vectors. I have a `Vec`, and I want to get a subset of its elements — that is, a slice. For example, I'm writing a program for data processing where there is a vector of numbers, and I need to work only with the first three elements or with a range from 2 to 5. I tried different approaches, but the compiler gives errors. Here is my code: ```rust fn main() { let numbers = vec![10, 20, 30, 40, 50, 60]; // Want to get a slice with indices 1..3 (20, 30, 40) let slice = numbers[1..4]; // Error! println!("{:?}", slice); } ``` The compiler says something about `Index` and `Range` traits — I don't quite understand what that means. I also heard that there is a difference between `&[T]` and `Vec`, but how to properly convert them