linux 隐式类型转换,Rust类型转换

Rust类型转换

Rust提供原始类型到隐式类型之间的转换(强制)。但是,显式类型转换可以使用关键字as进行。

整数类型之间的转换规则遵循C约定, 除了在C是未定义行为的转换。所有类型转换整型的行为在Rust都很好的定义。

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;

println!("Casting: {} -> {} -> {}", decimal, integer, character);

// when casting any value to an unsigned type, T,

// std::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

println!("1000 as a u8 is : {}", 1000 as u8);

// -1 + 256 = 255

println!(" -1 as a u8 is : {}", (-1i8) as u8);

// For positive numbers, this is the same as the modulus

println!("1000 mod 256 is : {}", 1000 % 256);

// When casting to a signed type, the result is the same as

// first casting to the corresponding unsigned type then

// taking the two's complement.

// Unless it already fits, of course.

println!(" 128 as a i16 is: {}", 128 as i16);

// 128 as u8 -> 128, whose two's complement in eight bits is:

println!(" 128 as a i8 is : {}", 128 as i8);

// repeating the example above

// 1000 as u8 -> 232

println!("1000 as a i8 is : {}", 1000 as i8);

// and the two's complement of 232 is -24

println!(" 232 as a i8 is : {}", 232 as i8);

}

¥ 我要打赏

纠错/补充

收藏

上一篇:

加QQ群啦,易百教程官方技术学习群

注意:建议每个人选自己的技术方向加群,同一个QQ最多限加 3 个群。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值