簡體   English   中英

如何在Rust中的鎖定結構成員上返回迭代器?

[英]How can I return an iterator over a locked struct member in Rust?

這是我可以得到的,使用租賃 ,部分基於如何將Chars迭代器存儲在與它迭代的String相同的結構中? 這里的區別在於鎖定成員的get_iter方法必須采用可變的自引用。

我不喜歡使用租賃:我對使用reffersowning_ref的解決方案感到 滿意

PhantomData存在這里只是讓MyIter熊到正常壽命的關系MyIterable ,這件事上迭代。

我也嘗試將#[rental]更改為#[rental(deref_mut_suffix)]並將#[rental(deref_mut_suffix)]的返回類型MyIterable.get_iterBox<Iterator<Item=i32> + 'a>但這給了我其他生命周期錯誤,這些錯誤源於宏我無法破譯。

#[macro_use]
extern crate rental;

use std::marker::PhantomData;

pub struct MyIterable {}

impl MyIterable {
    // In the real use-case I can't remove the 'mut'.
    pub fn get_iter<'a>(&'a mut self) -> MyIter<'a> {
        MyIter {
            marker: PhantomData,
        }
    }
}

pub struct MyIter<'a> {
    marker: PhantomData<&'a MyIterable>,
}

impl<'a> Iterator for MyIter<'a> {
    type Item = i32;
    fn next(&mut self) -> Option<i32> {
        Some(42)
    }
}

use std::sync::Mutex;

rental! {
    mod locking_iter {
        pub use super::{MyIterable, MyIter};
        use std::sync::MutexGuard;

        #[rental]
        pub struct LockingIter<'a> {
            guard: MutexGuard<'a, MyIterable>,
            iter: MyIter<'guard>,
        }
    }
}

use locking_iter::LockingIter;

impl<'a> Iterator for LockingIter<'a> {
    type Item = i32;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.rent_mut(|iter| iter.next())
    }
}

struct Access {
    shared: Mutex<MyIterable>,
}

impl Access {
    pub fn get_iter<'a>(&'a self) -> Box<Iterator<Item = i32> + 'a> {
        Box::new(LockingIter::new(self.shared.lock().unwrap(), |mi| {
            mi.get_iter()
        }))
    }
}

fn main() {
    let access = Access {
        shared: Mutex::new(MyIterable {}),
    };
    let iter = access.get_iter();
    let contents: Vec<i32> = iter.take(2).collect();
    println!("contents: {:?}", contents);
}

正如用戶Rodrigo在評論中指出的那樣,解決方案只是將#[rental]更改為#[rental_mut]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM