let t = Vec!, then to get the grand-parent of node 2 would be t as usize]), and I wondered how it would fail if usize was less than 32 bits. The platform-dependent size of isize / usize is one reason why I'm asking this question - the original scenario was I wanted to convert from u32 to usize so I could represent a tree in a Vec (e.g. This is one of the few cases where Rust gives. A typical implementation would first down-cast this argument (throwing an. I'm using the following code because I know it will generate assembly for both steps without optimising it away to nothing. Downcasting is the process of taking an item of one type and casting it to a more specific type. Many programming language type systems support subtyping. What's the idiomatic (and safe) way to convert between numeric (and pointer) types? There are two parts to downcasting, a) calling some function to get a type's ID and casting the reference if it matches our type, and b) the actual typeid () function automatically implemented by the compiler. I found ToPrimitive and FromPrimitive which provide nice functions like to_u32() -> Option, but they're marked as unstable: Any other cast is unsupported and will fail to compile.īut 4294967296us as u32 will silently overflow and give a result of 0. But as we are using a dynamic trait (as an interface concept). A raw pointer value can be cast to or from any integral type or raw pointer type. Rust is saying, you can use the as keyword to convert between primitive types. What's the idiomatic way to convert from (say) a usize to a u32?įor example, casting using 4294967295us as u32 works and the Rust 0.12 reference docs on type casting sayĪ numeric value can be cast to any numeric type. The answers still contain valuable information. Command-Line Rust could be done after the Book as well it looks like to me, doesn't seem to be as advanced as Rust for Rustaceans. Editor's note: This question is from a version of Rust prior to 1.0 and references some items that are not present in Rust 1.0. Downcasting is Rusts method of converting a trait into a concrete type. Rust in Action on the other hand is good for OS level projects like kernels or networking, and Zero to Production is written for backend web development.
0 Comments
Leave a Reply. |