Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: How return this Box'd Iterator, borrowing from RefCell?
How return this Box'd Iterator, borrowing from RefCell?
โ Rust ๐ 2025-08-28 ๐ค surdeus ๐๏ธ 3Playground here. I had a variation of this code working, but now Iโve added some interior mutability to the Thing
, so my implementation of iter_children
for Thing
is no longer good enough. The goal is to return from iter_children
an abstract iterator over Rc<dyn Node>
items.
Is there a way to adjust this code so it works with the borrowed state
? Maybe with complicated iterators like this it would be easier to use an โinternalโ iterator โ ie, pass a dyn Fn(&dyn Node) โ ()
to the iter_children
function, as opposed to trying to return in iterator?
use std::rc::Rc;
use std::cell::{Ref, RefCell};
type ChildIter<'a> = Box<dyn DoubleEndedIterator<Item = Rc<dyn Node + 'static>> + 'a>;
trait Node {
fn iter_children(&self) -> Option<ChildIter>;
}
struct Thing {
state: RefCell<State>
}
struct ChildInfo {
child: Rc<dyn Node>,
other: u32,
}
struct State {
nodes: Vec<ChildInfo>
}
impl Node for Thing {
fn iter_children(&self) -> Option<ChildIter> {
let b: Ref<State> = self.state.borrow();
Some( Box::new( b.nodes.iter().map(|info| info.child.clone())) )
}
}
The error:
error[E0515]: cannot return value referencing local variable `b`
--> src/main.rs:26:9
|
26 | Some( Box::new( b.nodes.iter().map(|info| info.child.clone())) )
| ^^^^^^^^^^^^^^^^-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| | |
| | `b` is borrowed here
| returns a value referencing data owned by the current function
2 posts - 2 participants
๐ท๏ธ Rust_feed