如何实现Rust的Copy特性?

时间:2016-02-17 13:51:13

标签: rust traits

我试图在Rust中初始化一个结构数组:

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

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

// Initialise the array, but failed.
let data = [RoadPoint { direction: Direction::East, index: 1 }; 4]; 

当我尝试编译时,编译器抱怨Copy特征未实现:

error[E0277]: the trait bound `main::RoadPoint: std::marker::Copy` is not satisfied
  --> src/main.rs:15:16
   |
15 |     let data = [RoadPoint { direction: Direction::East, index: 1 }; 4]; 
   |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::marker::Copy` is not implemented for `main::RoadPoint`
   |
   = note: the `Copy` trait is required because the repeated element will be copied

如何实施Copy特质?

2 个答案:

答案 0 :(得分:23)

您不必自己实施Copy;编译器可以为你派生出来:

#[derive(Copy, Clone)]
enum Direction {
    North,
    East,
    South,
    West,
}

#[derive(Copy, Clone)]
struct RoadPoint {
    direction: Direction,
    index: i32,
}

请注意,实现Copy的每种类型都必须实现CloneClone也可以派生出来。

答案 1 :(得分:9)

只需在枚举前添加@Override public void onBindViewHolder(final DataObjectHolder holder, int position) { int listType = getItemViewType(position); final ProductList item = data.get(position); if (listType == 0) { final List<Product> lstProducts = GetProducts(item.products); final MyPagerAdapter myAdapter = new MyPagerAdapter(ctx, lstProducts); holder.viewPager.setAdapter(myAdapter); myAdapter.notifyDataSetChanged(); // this changes nothing also.. } else { // removed.. } }

如果你真的想要,你也可以

#[derive(Copy, Clone)]

derive-attribute在幕后做同样的事情。