I would like to write a function that takes an Iterator<Item = Box<dyn Any>>
and returns a Vec<Box<dyn Any>>
as result, doing something with each of the items the iterator yields.
Consider the following code:
#![allow(dead_code, unused_variables)]
use std::any::Any;
#[derive(Debug)]
struct S<T> {
field: T,
}
fn wrap<T>(
elements: impl IntoIterator<IntoIter = impl Iterator<Item = T>>,
) -> Vec<S<T>> {
let mut vec = Vec::new();
for element in elements {
vec.push(S { field: element });
}
vec
}
fn dyn_wrap(
elements: impl IntoIterator<
IntoIter = impl Iterator<Item = Box<dyn Any>>,
>,
) -> Vec<Box<dyn Any>> {
todo!("How to implement this?")
}
fn main() {
let a = wrap([1, 2]);
println!("{a:?}");
let b = wrap(["Hello", "World"]);
println!("{b:?}");
let c = dyn_wrap(vec![
Box::new(7) as Box<dyn Any>,
Box::new("seven") as Box<dyn Any>,
]);
println!("{c:?}");
}
Output:
[S { field: 1 }, S { field: 2 }]
[S { field: "Hello" }, S { field: "World" }]
Errors:
Compiling playground v0.0.1 (/playground)
Finished dev [unoptimized + debuginfo] target(s) in 1.24s
Running `target/debug/playground`
thread 'main' panicked at 'not yet implemented: How to implement this?', src/main.rs:25:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Is it possible to implement dyn_wrap
akin to wrap
?