当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Rust Box.downcast用法及代码示例


本文简要介绍rust语言中 std::boxed::Box.downcast 的用法。

用法

pub fn downcast<T>(self) -> Result<Box<T, A>, Box<dyn Any + 'static, A>> where    T: Any,

尝试将盒子向下转换为具体类型。

例子

use std::any::Any;

fn print_if_string(value: Box<dyn Any>) {
    if let Ok(string) = value.downcast::<String>() {
        println!("String ({}): {}", string.len(), string);
    }
}

let my_string = "Hello World".to_string();
print_if_string(Box::new(my_string));
print_if_string(Box::new(0i8));

相关用法


注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 std::boxed::Box.downcast。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。