首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用返回可变引用的迭代器创建自己的数据结构?

如何使用返回可变引用的迭代器创建自己的数据结构?
EN

Stack Overflow用户
提问于 2014-09-09 02:15:44
回答 1查看 5.6K关注 0票数 41

我已经在Rust中创建了一个数据结构,我想为它创建迭代器。不可变的迭代器非常简单。我目前有这个,它工作得很好:

代码语言:javascript
复制
// This is a mock of the "real" EdgeIndexes class as
// the one in my real program is somewhat complex, but
// of identical type

struct EdgeIndexes;

impl Iterator for EdgeIndexes {
    type Item = usize;
    fn next(&mut self) -> Option<Self::Item> {
        Some(0)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (0, None)
    }
}

pub struct CGraph<E> {
    nodes: usize,
    edges: Vec<E>,
}

pub struct Edges<'a, E: 'a> {
    index: EdgeIndexes,
    graph: &'a CGraph<E>,
}

impl<'a, E> Iterator for Edges<'a, E> {
    type Item = &'a E;

    fn next(&mut self) -> Option<Self::Item> {
        match self.index.next() {
            None => None,
            Some(x) => Some(&self.graph.edges[x]),
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.index.size_hint()
    }
}

我还想创建一个返回可变引用的迭代器。我试过这样做,但找不到编译它的方法:

代码语言:javascript
复制
pub struct MutEdges<'a, E: 'a> {
    index: EdgeIndexes,
    graph: &'a mut CGraph<E>,
}

impl<'a, E> Iterator for MutEdges<'a, E> {
    type Item = &'a mut E;

    fn next(&mut self) -> Option<&'a mut E> {
        match self.index.next() {
            None => None,
            Some(x) => self.graph.edges.get_mut(x),
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.index.size_hint()
    }
}

编译此命令会导致以下错误:

代码语言:javascript
复制
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
  --> src/lib.rs:54:24
   |
54 |             Some(x) => self.graph.edges.get_mut(x),
   |                        ^^^^^^^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 51:5...
  --> src/lib.rs:51:5
   |
51 | /     fn next(&mut self) -> Option<&'a mut E> {
52 | |         match self.index.next() {
53 | |             None => None,
54 | |             Some(x) => self.graph.edges.get_mut(x),
55 | |         }
56 | |     }
   | |_____^
note: ...so that reference does not outlive borrowed content
  --> src/lib.rs:54:24
   |
54 |             Some(x) => self.graph.edges.get_mut(x),
   |                        ^^^^^^^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 48:6...
  --> src/lib.rs:48:6
   |
48 | impl<'a, E> Iterator for MutEdges<'a, E> {
   |      ^^
   = note: ...so that the expression is assignable:
           expected std::option::Option<&'a mut E>
              found std::option::Option<&mut E>

我不确定如何解释这些错误,以及如何更改代码以允许MutEdges返回可变引用。

链接到playground with code

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-09-09 23:34:48

你不能编译它,因为可变引用比不可变引用更严格。说明这个问题的一个简短版本是:

代码语言:javascript
复制
struct MutIntRef<'a> {
    r: &'a mut i32
}

impl<'a> MutIntRef<'a> {
    fn mut_get(&mut self) -> &'a mut i32 {
        &mut *self.r
    }
}

fn main() {
    let mut i = 42;
    let mut mir = MutIntRef { r: &mut i };
    let p = mir.mut_get();
    let q = mir.mut_get();
    println!("{}, {}", p, q);
}

这会产生相同的错误:

代码语言:javascript
复制
error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
 --> src/main.rs:7:9
  |
7 |         &mut *self.r
  |         ^^^^^^^^^^^^
  |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 6:5...
 --> src/main.rs:6:5
  |
6 | /     fn mut_get(&mut self) -> &'a mut i32 {
7 | |         &mut *self.r
8 | |     }
  | |_____^
note: ...so that reference does not outlive borrowed content
 --> src/main.rs:7:9
  |
7 |         &mut *self.r
  |         ^^^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 5:6...
 --> src/main.rs:5:6
  |
5 | impl<'a> MutIntRef<'a> {
  |      ^^
note: ...so that reference does not outlive borrowed content
 --> src/main.rs:7:9
  |
7 |         &mut *self.r
  |         ^^^^^^^^^^^^

如果我们看看main函数,我们会得到两个可变引用pq,这两个引用都是i的内存位置的别名。这是不允许的。在Rust中,我们不能有两个可变的引用作为别名并且都是可用的。这种限制的动机是观察到突变和别名在内存安全方面不能很好地协同工作。所以,编译器拒绝该代码是件好事。如果像这样编译,很容易得到各种内存损坏错误。

Rust避免这种危险的方法是保持最多一个可变引用可用。因此,如果你想基于对Y的可变引用创建对X的可变引用,其中X归Y所有,我们最好确保只要对X的引用存在,我们就不能再接触其他对Y的引用。在Rust中,这是通过生命周期和借款实现的。在这种情况下,编译器认为原始引用是被借用的,这也会影响结果引用的生存期参数。如果我们改变

代码语言:javascript
复制
fn mut_get(&mut self) -> &'a mut i32 {
    &mut *self.r
}

代码语言:javascript
复制
fn mut_get(&mut self) -> &mut i32 { // <-- no 'a anymore
    &mut *self.r // Ok!
}

编译器会停止对这个get_mut函数的抱怨。它现在返回一个带有生命周期参数的引用,该参数与&self匹配,而不再与'a匹配。这使得mut_get成为一个“借用”self的函数。这就是为什么编译器会抱怨一个不同的位置:

代码语言:javascript
复制
error[E0499]: cannot borrow `mir` as mutable more than once at a time
  --> src/main.rs:15:13
   |
14 |     let p = mir.mut_get();
   |             --- first mutable borrow occurs here
15 |     let q = mir.mut_get();
   |             ^^^ second mutable borrow occurs here
16 |     println!("{}, {}", p, q);
   |                        - first borrow later used here

显然,编译器确实认为mir是被借用的。这很好。这意味着现在只有一种方法可以到达i的内存位置:p

现在您可能想知道:标准库的作者是如何编写可变向量迭代器的?答案很简单:他们使用了不安全的代码。别无他法。Rust编译器根本不知道,每当您向可变向量迭代器请求下一个元素时,您每次都会得到一个不同的引用,并且永远不会两次得到相同的引用。当然,我们知道这样的迭代器不会给你两次相同的引用,这使得提供你习惯的这种接口是安全的。我们不需要“冻结”这样的迭代器。如果迭代器返回的引用不重叠,则不必借用迭代器来访问元素是安全的。在内部,这是使用不安全的代码(将原始指针转换为引用)完成的。

针对您的问题的easy 解决方案可能依赖于MutItems。这已经是一个向量上的库提供的可变迭代器。因此,您可以只使用该类型而不是您自己的自定义类型,或者您可以将其包装在自定义迭代器类型中。如果你因为某些原因不能做到这一点,你将不得不写你自己的不安全代码。如果你这样做了,请确保

  • ,你不会创建多个可变引用的别名。如果您这样做了,这将违反Rust规则并调用未定义的behavior.
  • You不要忘记使用PhantomData类型告诉编译器您的迭代器是类似引用的类型,其中不允许用更长的生命周期替换生命周期,否则可能会创建一个悬空的迭代器。
票数 43
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25730586

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档