Can casting in safe Rust ever lead to a runtime error? -
i'm fiddling bit any
, casting deeper understanding of rust. c# i'm used fact casting can lead runtime exceptions because casting in c# means dear compiler, trust me, know i'm doing please cast int32
because know work.
however, if you're doing invalid cast program blow exception @ runtime. wondering if casting in (safe) rust can equally lead runtime exception.
so, came code try out.
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); // gives 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 cast (which lead runtime error) //let z = v[1] i32; } }
my observation far compiler seems prevent me kind of runtime exceptions because have cast through downcast_ref
returns option
makes safe again. sure, can unwrap
on none
blow that's not point ;)
the compiler prevents me writing let z = v[1] i32;
lead runtime error. so, correct assume casting in safe rust never result in runtime error?
i know preventing runtime errors rust makes perfect sense, want validate observation :)
casting as
in rust limited. allows casting between primitive numeric , character types, between pointers , references , creating trait objects out of values of concrete types, , that's - as
not overloadable, example. therefore, casting as
panic-free, though can observe numeric overflows if you're casting value can't represented in target type, may or may not desirable.
in rust there no such thing cast operator c# or java. closest thing std::mem::transmute()
lot reinterpret_cast
c++. unsafe
, however, , has limitations - can transform values of types having same size.
Comments
Post a Comment