Rust by Example | страница 20
>fn main() {
>let mut _mutable_integer = 7i32;
>{
>// Shadowing by immutable `_mutable_integer`
>let _mutable_integer = _mutable_integer;
>// Error! `_mutable_integer` is frozen in this scope
>_mutable_integer = 50;
>// FIXME ^ Comment out this line
>// `_mutable_integer` goes out of scope
>}
>// Ok! `_mutable_integer` is not frozen in this scope
>_mutable_integer = 3;
>}
>הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה
>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Rust provides several mechanisms to change or define the type of primitive and user defined types. The following sections cover:
• Casting between primitive types
• Specifying the desired type of literals
• Using type inference
• Aliasing types
Rust provides no implicit type conversion (coercion) between primitive types. But, explicit type conversion (casting) can be performed using the as keyword.
Rules for converting between integral types follow C conventions generally, except in cases where C has undefined behavior. The behavior of all casts between integral types is well defined in Rust.
>// Suppress all warnings from casts which overflow.
>#![allow(overflowing_literals)]
>fn main() {
>let decimal = 65.4321_f32;
>// Error! No implicit conversion
>let integer: u8 = decimal;
>// FIXME ^ Comment out this line
>// Explicit conversion
>let integer = decimal as u8;
>let character = integer as char;
>// Error! There are limitations in conversion rules. A float cannot be directly converted to a char.
>let character = decimal as char;
>// FIXME ^ Comment out this line
>println!("Casting: {} -> {} -> {}", decimal, integer, character);
>// when casting any value to an unsigned type, T,
>// T::MAX + 1 is added or subtracted until the value
>// fits into the new type
>// 1000 already fits in a u16
>println!("1000 as a u16 is: {}", 1000 as u16);
>// 1000 - 256 - 256 - 256 = 232
>// Under the hood, the first 8 least significant bits (LSB) are kept,
>// while the rest towards the most significant bit (MSB) get truncated.