How do I get a slice of a Vec in Rust?

前端 未结 2 745
执笔经年
执笔经年 2020-12-24 10:55

I can not find within the documentation of Vec how to retrieve a slice from a specified range.

Is there something like this in the standard li

2条回答
  •  我在风中等你
    2020-12-24 11:27

    The documentation for Vec covers this in the section titled "slicing".

    You can create a slice of a Vec or array by indexing it with a Range (or RangeInclusive, RangeFrom, RangeTo, RangeToInclusive, or RangeFull), for example:

    fn main() {
        let a = vec![1, 2, 3, 4, 5];
    
        // With a start and an end
        println!("{:?}", &a[1..4]);
    
        // With a start and an end, inclusive
        println!("{:?}", &a[1..=3]);
    
        // With just a start
        println!("{:?}", &a[2..]);
    
        // With just an end
        println!("{:?}", &a[..3]);
    
        // With just an end, inclusive
        println!("{:?}", &a[..=2]);
    
        // All elements
        println!("{:?}", &a[..]);
    }
    

提交回复
热议问题