有没有办法将多个非复制元素移出数组?

时间:2018-08-23 13:16:43

标签: rust

有没有办法像[a, b] = map那样解构数组,因此将两个数组元素移到ab中,以便稍后a和{{1} }可以移到另一个函数中(在这种情况下,例如b

printme
enum Direction {
    North,
    East,
    South,
    West,
}

struct RoadPoint {
    direction: Direction,
    index: i32,
}

fn printme(a: RoadPoint, b: RoadPoint) {
    println!("First: {}", a.index);
}

fn main() {
    let mut map: [RoadPoint; 2] = [
        RoadPoint {
            direction: Direction::North,
            index: 0,
        },
        RoadPoint {
            direction: Direction::North,
            index: 0,
        },
    ];

    for i in 1..3 {
        map[i].index = 10;
    }

    //move out
    printme(map[0], map[1])
}

我知道可以实现error[E0508]: cannot move out of type `[RoadPoint; 2]`, a non-copy array --> src/main.rs:34:13 | 34 | printme(map[0], map[1]) | ^^^^^^ cannot move out of here error[E0508]: cannot move out of type `[RoadPoint; 2]`, a non-copy array --> src/main.rs:34:21 | 34 | printme(map[0], map[1]) | ^^^^^^ cannot move out of here 特征的事实,但是在这种情况下,我实际上不需要数据副本。因此,我正在寻找更清洁的解决方案。

1 个答案:

答案 0 :(得分:1)

如果您将夜间Rust使用具有非词法生存期功能和固定长度的切片模式,则可以使其正常工作:

#![feature(nll)]

enum Direction {
    North,
    East,
    South,
    West,
}

struct RoadPoint {
    direction: Direction,
    index: i32,
}

fn printme(a: RoadPoint, b: RoadPoint) {
    println!("First: {}", a.index);
    println!("Second: {}", b.index);
}

fn main() {
    let map: [RoadPoint; 2] = [
        RoadPoint {
            direction: Direction::North,
            index: 0,
        },
        RoadPoint {
            direction: Direction::North,
            index: 0,
        },
    ];

    let [a, b] = map;
    printme(a, b);
}

如果没有#![feature(nll)],它将失败,并显示以下信息:

error[E0382]: use of moved value: `map[..]`
  --> src/main.rs:30:13
   |
30 |     let [a, b] = map;
   |          -  ^ value used here after move
   |          |
   |          value moved here
   |
   = note: move occurs because `map[..]` has type `RoadPoint`, which does not implement the `Copy` trait