简体   繁体   English

在返回的结构中捕获迭代器

[英]capture a iterator in a returned struct

Newbie here, still struggling with ownership.这里的新手,仍在为所有权而苦苦挣扎。

I would like to know how I can, in a function, returns a borrow from a struct wrapped in another struct.我想知道如何在 function 中从包装在另一个结构中的结构返回借用。 Here is an example:这是一个例子:

struct Data {
    data: [String; 10]
}

struct DataIterator<'a> {
    value: &'a std::slice::IterMut<'a, String>
}

impl Data {
    fn get_string(&mut self) -> DataIterator {
        let result = DataIterator {
            value: &self.data.iter_mut()
        };
        return result;
    }
}

Here is a link to the playground .这是游乐场的链接。

The idea would be to get a usable iterator, where the data from the Data struct is borrowed, and can be modified, and then, when the return value of the get_string function is dropped, the borrow stops.这个想法是获得一个可用的迭代器,其中从 Data 结构中借用数据,并且可以修改,然后,当 get_string function 的返回值被删除时,借用停止。

However, I'm getting an error where the data cannot be returned as it is owned by the function.但是,我收到一个错误,因为数据归 function 所有,因此无法返回数据。

I've tried my best to simplify the issue, as in my case it gets more complicated and I didn't want to give lots of useless information, but I'm trying to return several iterator from the original struct and borrow the fields of the struct doing so.我已尽力简化问题,因为在我的情况下它变得更加复杂,我不想提供很多无用的信息,但我试图从原始结构返回几个迭代器并借用字段结构这样做。

Is there a way to "capture" the iterator and borrow it using such a function?有没有办法“捕获”迭代器并使用这样的 function 借用它?

The get_string() function creates the iterator; get_string get_string() function创建迭代器; it as a temporary value, and returning a reference to it is forbidden (it would be dangling).它作为一个临时值,并且禁止返回对它的引用(它会悬空)。

I don't think you need to store a reference to the iterator.我认为您不需要存储对迭代器的引用。 You could simply store the iterator as a value.您可以简单地将迭代器存储为一个值。

It however refers to the original container.然而,它指的是原始容器。 The 'a in IterMut is implicitly the lifetime of &mut self in get_string() . IterMut中的'a隐含地是&mut self在 get_string get_string()中的生命周期。 Then, when this DataIterator will be dropped, the exclusive borrow of the Data will stop.然后,当这个DataIterator将被删除时, Data的独占借用将停止。

struct Data {
    data: [String; 10],
}

struct DataIterator<'a> {
    value: std::slice::IterMut<'a, String>,
}

impl Data {
    fn get_string(&mut self) -> DataIterator {
        DataIterator {
            value: self.data.iter_mut(),
        }
    }
}

fn main() {
    let mut d = Data {
        data: Default::default(),
    };
    //
    // a first exclusive-borrow of d starts here...
    d.get_string().value.enumerate().for_each(|(i, e)| {
        *e = format!("elem {}", i);
    });
    // ... the first exclusive-borrow of d stops here
    //
    // a second exclusive-borrow of d starts here...
    let it = d.get_string();
    // println!("CANNOT borrow data: {:?}", d.data);
    it.value.for_each(|e| {
        println!("{:?}", e);
    });
    // ... it is not used anymore below this line,
    // ... the second exclusive-borrow of d stops here
    //
    println!("can borrow data: {:?}", d.data);
}
/*
"elem 0"
"elem 1"
"elem 2"
"elem 3"
"elem 4"
"elem 5"
"elem 6"
"elem 7"
"elem 8"
"elem 9"
can borrow data: ["elem 0", "elem 1", "elem 2", "elem 3", "elem 4", "elem 5", "elem 6", "elem 7", "elem 8", "elem 9"]
*/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM