3个稳定版本
1.0.2 | 2020年10月25日 |
---|
#253 in 无标准库
5KB
as_any_min
这是一个非常小的crate,通过允许你轻松地将特质对象向上转换为Any,使与实现了Any特质的特质一起工作变得更加容易。
示例
use core::any::Any;
use as_any_min::AsAny;
struct MyStruct;
trait MyTrait {}
impl MyTrait for MyStruct {}
/* Note that AsAny is automatically implemented for all
structs that implement Any, so there is no need to
implement it manually (in fact it won't compile if
you try to) */
fn main() {
// my_variable is now a trait object, which is the
// main use case for the AsAny trait.
let my_variable: &dyn MyTrait = &MyStruct;
let my_any_variable: &dyn Any = my_variable.as_any();
}
不使用AsAny
由于Rust(目前)没有内置的方式从特质对象向上转换为另一个特质(例如Any
),这段代码将无法编译。
use core::any::Any;
struct MyStruct;
trait MyTrait {}
impl MyTrait for MyStruct {}
fn main() {
let my_variable: &dyn MyTrait = &MyStruct;
let my_any_variable: &dyn Any = my_variable;
}
许可证:MIT