Any为了更深入地了解Rust,我正在努力摆弄并投入.从C#我习惯了这样一个事实,即转换可能会导致运行时异常,因为在C#中进行转换基本上意味着亲爱的编译器,相信我,我知道我在做什么请将其转换成一个int32因为我知道它会起作用.
但是,如果您正在执行无效的转换,程序将在运行时以异常方式爆炸.所以我想知道(安全)Rust中的转换是否同样会导致运行时异常.
所以,我想出了这个代码来试一试.
use std::any::Any;
fn main() {
let some_int = 4;
let some_str = "foo";
{
let mut v = Vec::<&Any>::new();
v.push(&some_int);
v.push(&some_str);
// this gives a None
let x = v[0].downcast_ref::<String>();
println!("foo {:?}", x);
//this gives Some(4)
let y = v[0].downcast_ref::<i32>();
println!("foo {:?}", y);
//the compiler doesn't let me do this cast (which would lead to a runtime error)
//let z = v[1] as i32;
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止我的观察是编译器似乎阻止了我这种运行时异常,因为我必须通过downcast_ref哪个返回Option使得它再次安全.当然,我可以unwrap用它 …