为什么 `128u8.checked_shl(1)` return `Some(0)`?
Why does `128u8.checked_shl(1)` return `Some(0)`?
我的印象是整数类型的 .checked_*(_)
方法可以帮助避免溢出。然而,.checked_shl(u32)
方法愉快地移出了上面示例的最后一位。
我的印象有误吗? for是什么方法?
(还想补充一点以避免轮班溢出,可以至少检查无符号类型是否 ((~0) >> rhs) >= self
)
因为它只检查偏移量。来自docs,
None
if rhs
is larger than or equal to the number of bits in self
.
所以根据设计,它允许您移出位,它只是不允许您使用无效的移位量(或者,它允许您,但您得到 None
)。
我的印象是整数类型的 .checked_*(_)
方法可以帮助避免溢出。然而,.checked_shl(u32)
方法愉快地移出了上面示例的最后一位。
我的印象有误吗? for是什么方法?
(还想补充一点以避免轮班溢出,可以至少检查无符号类型是否 ((~0) >> rhs) >= self
)
因为它只检查偏移量。来自docs,
None
ifrhs
is larger than or equal to the number of bits inself
.
所以根据设计,它允许您移出位,它只是不允许您使用无效的移位量(或者,它允许您,但您得到 None
)。