【问题标题】:Why am I allowed to call take() on a mutable reference to an iterator?为什么允许我在对迭代器的可变引用上调用 take()?
【发布时间】:2021-03-30 18:16:49
【问题描述】:

我试图在迭代器上使用 take(n) 对第一个 n 项执行某些操作,然后对其余项执行不同的操作(for ... in ... 循环)。

在声明中:

fn take(self, n: usize) -> Take<Self>

self 作为第一个参数告诉我 take() 必须用于拥有的值,而不是引用 (&amp;self) 或可变引用 (&amp;mut self)。

by_ref() 的文档说它返回一个可变引用,并且

这对于允许在仍然应用迭代器适配器时很有用 保留原始迭代器的所有权。

它包含一个使用by_ref().take(n) 的示例,然后继续使用迭代器(就像我想要的那样)。

我的问题是,为什么允许我在可变引用上调用 take()(而不是要求拥有值)?换句话说,take() 不应该被声明为:

fn take(&mut self, n: usize) -> Take<Self>

使其可以与可变引用一起使用?

我应该一直在寻找什么声明会告诉我这是可能的?

【问题讨论】:

    标签: rust reference iterator borrowing


    【解决方案1】:

    Rust 将 T、&amp;T 和 &amp;mut T 视为单独的类型。作为单独的类型,我们可以为它们中的每一个实现不同的方法。示例:

    struct Struct;
    
    trait Printable {
        fn print(self);
    }
    
    impl Printable for Struct {
        fn print(self) {
            println!("I'm an owned Struct");
        }
    }
    
    impl Printable for &Struct {
        fn print(self) {
            println!("I'm a Struct reference");
        }
    }
    
    fn main() {
        let s = Struct;
        let s_ref = &Struct;
        s.print();
        s_ref.print();
    }
    

    如果我们对得到的 trait 方法进行脱糖:

    fn print(self: Self) { /* implementation */ }
    

    其中Self 等于实现类型,在Struct 的情况下为:

    fn print(self: Struct) { /* implementation */ }
    

    在&amp;Struct的情况下是:

    fn print(self: &Struct) { /* implementation */ }
    

    所以真的self 可以是拥有的类型或不可变引用或可变引用。您可以在对Iterators 的可变引用上调用take 的原因是because of this generic blanket impl which implements the Iterator trait on all mutable references to Iterators:

    impl<'_, I> Iterator for &'_ mut I where I: Iterator + ?Sized { /* implementation */ }
    

    让我们以vec.into_iter() 为例。由于它返回实现了Iterator 的std::vec::IntoIter,我们知道take 的这个实现必须存在:

    take(self: std::vec::IntoIter, n: usize) -> Take<std::vec::IntoIter> { /* implementation */ }
    

    然而,我们也知道take 的&amp;mut std::vec::IntoIter 的实现必须存在,因为它将由上面提到的通用毯子impl 自动生成,并且该实现的签名如下所示:

    take(self: &mut std::vec::IntoIter, n: usize) -> Take<&mut std::vec::IntoIter> { /* implementation */ }
    

    这就是为什么您可以在对实现Iterator 的任何类型的任何可变引用上调用take。

    【讨论】:

      猜你喜欢
      • 2012-06-28
      • 2016-11-26
      • 1970-01-01
      • 2020-05-10
      • 2016-08-26
      • 2021-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多