【问题标题】:Is there a way to move multiple non-Copy elements out of an array? [duplicate]有没有办法将多个非复制元素移出数组? [复制]
【发布时间】:2019-01-29 21:17:09
【问题描述】:

有没有办法像[a, b] = map这样解构数组,让两个数组元素移动到ab,这样以后ab就可以移动到另一个函数中(比如@ 987654326@ 在这种情况下)。

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

我知道我可以实现 Copy 特征,但在这种情况下我实际上不需要数据副本。因此,我正在寻找更清洁的解决方案。

【问题讨论】:

  • 您的某些代码不是很惯用:更喜欢直接迭代而不是集合而不是索引范围 (for point in &mut map { })。

标签: rust


【解决方案1】:

如果您使用具有 非词法生命周期 功能和固定长度切片模式的 nightly 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

【讨论】:

  • 非常感谢。这就是我一直在寻找的。​​span>
  • 是否还有非夜间版本的解决方法?我可以在 usafe 模式下重铸指针吗?
  • Rust 中非 Copy 类型的数组不是很灵活。也许你可以做类似let mut v : Vec<_> = (Box::new(map) as Box<[_]>).into(); let b = v.pop().unwrap(); let a = v.pop().unwrap(); 的事情。但是,如果您对此感兴趣,那么您可以首先使用 Vec 而不是数组!
  • 非常感谢!是的,我可能会选择 Vec 和 pop()。这意味着数据存储在堆上。这会对性能产生任何影响吗?
  • 稳定版可以看split_at
猜你喜欢
  • 1970-01-01
  • 2019-11-08
  • 1970-01-01
  • 2020-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多