overflowing_add And overflowing_mul Report Carries

Get wrapped results and an overflow flag in one call: overflowing_add and overflowing_mul return the value modulo the type plus a carry boolean.

RustData Integrity

Code

rustsnippet
15 lines
fn main() {
    // overflowing_add:返回 (回绕值, 是否溢出),溢出也能拿到回绕结果
    let (sum, overflowed) = 250u8.overflowing_add(10);
    println!("250u8 + 10 = {sum} (overflowed: {overflowed})");

    let (fine, no_overflow) = 200u8.overflowing_add(10);
    println!("200u8 + 10 = {fine} (overflowed: {no_overflow})");

    // 乘法同理:255 * 2 回绕到 254 并标记溢出
    let (product, overflowed) = 255u8.overflowing_mul(2);
    println!("255u8 * 2 = {product} (overflowed: {overflowed})");

    // 与 checked 对比:checked 在溢出处给出 None,overflowing 给回绕值+标记
    println!("checked sum: {:?}", 250u8.checked_add(10));
}

How it works

overflowing_add And overflowing_mul Report Carries reduces to the function main.

Applying it

Running the file prints labeled results such as 250u8 + 10 =, 200u8 + 10 =, 255u8 * 2 = — each operation’s effect is visible in the output.

Statements that matter

let (product, overflowed) = 255u8.overflowing_mul(2);
let (fine, no_overflow) = 200u8.overflowing_add(10);
let (sum, overflowed) = 250u8.overflowing_add(10);

Interactive Tools for This Topic

FAQ

What does overflowing_add And overflowing_mul Report Carries print when run?
Invoke the file as-is — the `250u8 + 10 =`, `200u8 + 10 =`, `255u8 * 2 =` prefixes identify which step printed each line.