Open
Description
Code
#[derive(Debug)]
enum MyTreeNode {
Leaf,
VecNode(Vec<Self>),
}
impl MyTreeNode {
pub fn iter(&self) -> impl Iterator<Item = &Self> + '_ {
[self]
.into_iter()
.chain(self.nonrecursive_iter().flat_map(|e| e.iter()))
}
fn nonrecursive_iter(&self) -> Box<dyn Iterator<Item = &Self> + '_> {
match self {
Self::Leaf => Box::new([].into_iter()),
Self::VecNode(v) => Box::new(v.iter()),
}
}
}
fn main() {
let tree = MyTreeNode::VecNode(vec![
MyTreeNode::Leaf,
MyTreeNode::VecNode(vec![MyTreeNode::Leaf, MyTreeNode::Leaf]),
]);
for node in tree.iter() {
dbg!(node);
}
}
Current output
Compiling playground v0.0.1 (/playground)
error: concrete type differs from previous defining opaque type use
--> src/main.rs:9:9
|
9 | / [self]
10 | | .into_iter()
11 | | .chain(self.nonrecursive_iter().flat_map(|e| e.iter()))
| | ^
| | |
| |___________________________________________________________________expected `std::iter::Chain<std::array::IntoIter<&MyTreeNode, 1>, FlatMap<Box<dyn Iterator<Item = &MyTreeNode>>, impl Iterator<Item = &MyTreeNode> + '_, {closure@src/main.rs:11:54: 11:57}>>`, got `impl Iterator<Item = &MyTreeNode> + '_`
| this expression supplies two conflicting concrete types for the same opaque type
error: could not compile `playground` (bin "playground") due to 1 previous error
Desired output
Rationale and extra context
I believe the issue here is not that the expression returns two different types, but that it returns a single recursive type. Changing the iter()
function signature to return a boxed iterator makes the code compile. If I'm right, then I think some wording about boxing the output of recursive function calls makes sense (similar to the message you see if you recurse async function calls).
Other cases
Rust Version
rustc 1.84.0 (9fc6b4312 2025-01-07)
binary: rustc
commit-hash: 9fc6b43126469e3858e2fe86cafb4f0fd5068869
commit-date: 2025-01-07
host: aarch64-apple-darwin
release: 1.84.0
LLVM version: 19.1.5
Anything else?
No response