如何将元素移出装箱切片,并在此过程中消耗该切片?

Adr*_*her 8 rust

例如:

struct T(u32); // No Copy implementation

fn consume(t: T) {}

fn main() {
    let v = vec![T(1), T(2)];
    let s = v.into_boxed_slice();
    // Get a Box<[T]> from somewhere and consume it:
    for t in s {
        consume(t);
    }
}
Run Code Online (Sandbox Code Playgroud)

结果编译器错误:

struct T(u32); // No Copy implementation

fn consume(t: T) {}

fn main() {
    let v = vec![T(1), T(2)];
    let s = v.into_boxed_slice();
    // Get a Box<[T]> from somewhere and consume it:
    for t in s {
        consume(t);
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以使用盒装切片s.into_vec()构造一个,然后使用该向量。Vec这在性能方面接近于无操作,但有更优雅的方法吗?

She*_*ter 9

直接支持这一点有一个 Rust 问题:Box<[T]> 应该有一个 IntoIter 实现

在稳定的 Rust 中你能做的最好的事情就是将其转换为Vec

let v = Vec::from(s);
for t in v {
    consume(t);
}
Run Code Online (Sandbox Code Playgroud)

我不认为这会带来性能下降,因为转换到 基本上Vec会添加一个usize.


如果在编译时知道切片的长度,则可以将切片转换为 a Box<[T; N]>,然后用于array::IntoIter迭代:

use std::convert::TryInto;

let a: Box<[T; 2]> = match s.try_into() {
    Ok(a) => a,
    Err(_) => panic!("Not length 2"),
};

for t in std::array::IntoIter::new(*a) {
    consume(t);
}
Run Code Online (Sandbox Code Playgroud)