【问题标题】:Vector index: cannot move out of dereference向量索引:不能移出取消引用
【发布时间】:2014-09-28 13:19:52
【问题描述】:

我正在尝试通过实现一些基本数据结构来学习 Rust。在这种情况下,Matrix

struct Matrix<T> {
  pub nrows: uint,
  pub ncols: uint,
  pub rows: Vec<T>
}

现在,我想用这个函数转置Matrix

pub fn transpose(&self) -> Matrix<T> {
  let mut trans_matrix = Matrix::new(self.ncols, self.nrows);
  for i in range(0u, self.nrows - 1u) {
    for j in range(0u, self.ncols - 1u) {
      trans_matrix.rows[j*i] = self.rows[i*j]; // error
    }
  }
  trans_matrix
}

但我在标记线上收到此错误:

error: cannot move out of dereference (dereference is implicit, due to indexing)
error: cannot assign to immutable dereference (dereference is implicit, due to indexing)

所以我要做的是使trans_matrixrows 可变,并以某种方式修复取消引用错误。我该如何解决这个问题?谢谢。

【问题讨论】:

    标签: rust


    【解决方案1】:

    使用

    *trans_matrix.rows.get_mut(j * i) = self.rows[i * j];
    

    有效,但只是一种解决方法。我不知道IndexMut 需要多长时间才能按预期工作,或者是否已经工作,但这是前一段时间的首选方式

    【讨论】:

    • 信不信由你,我仍然有同样的错误:error: cannot move out of dereference (dereference is implicit, due to indexing) *trans_matrix.rows.get_mut(j * i) = self.rows[i * j];。此外,get_mut() 被标记为已弃用(使用索引)。
    • @tolgap: This gist 用我的设置编译,即使它抱怨死代码。请测试一下。
    • 该代码没有为我编译(同样的错误)。我正在使用rustc 0.12.0-nightly (c669411af)
    • rustc -v: rustc 0.12.0-nightly (2550243b4 2014-09-25 19:02:44 +0000) 给我。另外,我在发布评论几秒钟后更改了上述评论中的链接,因为我将错误的链接粘贴到其中,假设您阅读评论的时间超过了这几秒钟。你绝对试图编译this gist,对吧?
    • 其实我是 F5 的,所以我抓住了上一个链接。您的编辑有效。我认为原因在于我的Matrix::new 函数,我在其中为Matrix 结构创建了一个可变的rows 变量。当我改变它时,它起作用了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多