【问题标题】:Why does storing &str in a Box<dyn Any> and downcasting it to a &Box<&str> always result in None?为什么将 &str 存储在 Box<dyn Any> 中并将其向下转换为 &Box<&str> 总是会导致 None?
【发布时间】: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

据我了解,它向下转换为 &amp;str 并解包以提供 &amp;Box&lt;&amp;str&gt;,但它返回 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
}

我该怎么做?

【问题讨论】:

    标签: struct rust


    【解决方案1】:

    你没有在Any 中持有Box&lt;&amp;str&gt;。你在Any 中持有&amp;str。

    let string: &str = v[0]
        .downcast_ref::<&str>()
        .unwrap();
    
    println!("{}", string);
    
    let int: &i32 = v[1]
        .downcast_ref()  // Rust infers ::<i32>
        .unwrap();
    
    println!("{}", int);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多