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

前端 未结 2 736
执笔经年
执笔经年 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:12

    If you wish to convert the entire Vec to a slice, you can use deref coercion:

    fn main() {
        let a = vec![1, 2, 3, 4, 5];
        let b: &[i32] = &a;
    
        println!("{:?}", b);
    }
    

    This coercion is automatically applied when calling a function:

    fn print_it(b: &[i32]) {
        println!("{:?}", b);
    }
    
    fn main() {
        let a = vec![1, 2, 3, 4, 5];
        print_it(&a);
    }
    

    You can also call Vec::as_slice, but it's a bit less common:

    fn main() {
        let a = vec![1, 2, 3, 4, 5];
        let b = a.as_slice();
        println!("{:?}", b);
    }
    

    See also:

    • Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?

提交回复
热议问题