【问题标题】:How do I get a slice of a Vec<T> in Rust?如何在 Rust 中获得 Vec<T> 的一部分?
【发布时间】:2017-02-08 16:22:33
【问题描述】:

我在Vec&lt;T&gt; 的文档中找不到如何从指定范围检索切片。

标准库中是否有这样的东西:

let a = vec![1, 2, 3, 4];
let suba = a.subvector(0, 2); // Contains [1, 2];

【问题讨论】:

    标签: vector rust


    【解决方案1】:

    Vec 的文档在 the section titled "slicing" 中对此进行了介绍。

    您可以通过使用Range(或RangeInclusiveRangeInclusiveRangeFromRangeToRangeToInclusiveRangeFull)为Vecarray 创建一个slice ,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[..]);
    }
    

    【讨论】:

    • 没有明确结束索引的范围的行为是什么?它是否意味着范围到达向量的末尾(例如向量长度)?我找不到这个记录。
    • 是的,没错。它在SliceIndex impls 的文档中明确记录,例如impl SliceIndex&lt;str&gt; for RangeFrom&lt;usize&gt;:“从字节范围[begin, len) 返回给定字符串的一部分。等效于&amp;self[begin .. len]&amp;mut self[begin .. len]。”
    【解决方案2】:

    如果您想将整个Vec 转换为切片,可以使用deref coercion

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

    调用函数时会自动应用此强制:

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

    您也可以拨打Vec::as_slice,但它不太常见:

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

    另见:

    【讨论】:

    • +1 我喜欢.as_slice()[..] 好得多,因为它传达了意图。 (将 Vec 转换为切片,因为只有切片而不是 Vecs 实现 io::Read。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    • 2018-08-08
    • 2018-01-29
    相关资源
    最近更新 更多