【发布时间】:2021-10-08 21:57:19
【问题描述】:
我想创建一个结构向量,每个结构都包含一个可以具有任何(多个)类型的字段,也能够提取这些值。我试过这个:
use std::any::Any;
fn main() {
let mut v: Vec<Box<dyn Any>> = Vec::new();
v.push(Box::new("test"));
v.push(Box::new(3i32));
let string: &Box<&str> = &v[0].downcast_ref().unwrap(); // erroneous line
println!("{}", string);
let int: &Box<&i32> = &v[1].downcast_ref().unwrap(); // probably gives an error too
println!("{}", int);
}
应该打印出来
test
3
相反,它会恐慌:
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', src/main.rs:8:51
据我了解,它向下转换为 &str 并解包以提供 &Box<&str>,但它返回 None 值。
我尝试过其他东西,例如带有泛型的结构,但仅限于一种类型:
struct Item<T> {
item: T,
}
fn main() {
let mut v: Vec<Item<&str>> = Vec::new();
v.push(Item { item: "hi" });
v.push(Item { item: 3i32 }); // error because it can only be &str, not i32
}
我该怎么做?
【问题讨论】: