如何正确使用IndexMut特性?

时间:2014-08-20 07:39:13

标签: rust traits

我最近玩过rust并尝试为Point结构实现索引,因此some_point[2]会给我z坐标。

但是我无法获得下面的代码来编译。我错过了什么?

struct Point {
  x: int,
  y: int,
  z: int
}

impl IndexMut<uint, int> for Point {
  fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut int {
    & mut match *index {
      0 => self.x,
      1 => self.y,
      2 => self.z,
      _ => 0 //TODO: add proper error handling
    }
  }
}

这是我得到的错误:

[me@localhost rust]$ rustc blabla.rs && ./blabla
blabla.rs:25:11: 30:6 error: borrowed value does not live long enough
blabla.rs:25     & mut match *index {
blabla.rs:26       0 => self.x,
blabla.rs:27       1 => self.y,
blabla.rs:28       2 => self.z,
blabla.rs:29       _ => 0
blabla.rs:30     }
blabla.rs:24:63: 31:4 note: reference must be valid for the lifetime 'a as defined on the block at 24:62...
blabla.rs:24   fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut int {
blabla.rs:25     & mut match *index {
blabla.rs:26       0 => self.x,
blabla.rs:27       1 => self.y,
blabla.rs:28       2 => self.z,
blabla.rs:29       _ => 0
             ...
blabla.rs:24:63: 31:4 note: ...but borrowed value is only valid for the block at 24:62
blabla.rs:24   fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut int {
blabla.rs:25     & mut match *index {
blabla.rs:26       0 => self.x,
blabla.rs:27       1 => self.y,
blabla.rs:28       2 => self.z,
blabla.rs:29       _ => 0
             ...
error: aborting due to previous error

我很抱歉stackoverflow强迫我将错误信息格式化为代码。我希望它仍然可读。

1 个答案:

答案 0 :(得分:5)

你的匹配块复制self.x等,然后函数尝试返回一个可变引用(至少这是我的解释)。试试这个

match *index {
  0 => & mut self.x,
  1 => & mut self.y,
  2 => & mut self.z,
  _ => fail!("")
}