checked_shl checked_shr Width Guards
Shift safely with checked_shl and checked_shr: any shift amount at or beyond the type width yields None instead of masked, surprising bits.
Code
fn main() {
let byte: u8 = 0b0000_0001;
// 合法位移与普通 << 语义一致
println!("1 << 4 = {:#010b}", byte.checked_shl(4).unwrap());
// u8 的位宽是 8:位移量 ≥ 8 返回 None(普通 << 只取低 3 位做掩码)
println!("1 << 8 = {:?}", byte.checked_shl(8));
println!("1 << 9 = {:?}", byte.checked_shl(9));
println!("plain 1u8 << 9 = {:#010b}", 1u8 << 9); // 实际移 1 位
// 右移同样设防:255 >> 8 是 None,掩码版 >> 0 原样返回
println!("255 >> 7 = {:?}", 255u8.checked_shr(7));
println!("255 >> 8 = {:?}", 255u8.checked_shr(8));
// 带符号类型:负数右移保持符号,checked_shr 一样
println!("-16 >> 2 = {:?}", (-16i32).checked_shr(2));
println!("-16 >> 32 = {:?}", (-16i32).checked_shr(32));
// 与 rotate 家族对比:rotate 移出的位绕回另一侧,永远合法
println!("rotate_left(8) on u8 = {:#010b}", byte.rotate_left(8));
}Masked shifts versus guarded ones
A single main walks through shift and rotate comparisons.
Points of care
- checked_shl, checked_shr, and rotate_left are primitive methods — nothing to add.
Applying it
The entry-point signature is fn main()
The run labels each probe (1 << 4 =, 1 << 8 =, 1 << 9 =), so masked versus guarded shifts stay distinct.
Probe results worth reading
let byte: u8 = 0b0000_0001;
Interactive Tools for This Topic
FAQ
- What does checked_shl checked_shr Width Guards print when run?
- Run it as a complete program — the output lines carry labels such as `1 << 4 =`, `1 << 8 =`, `1 << 9 =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.