div_euclid And rem_euclid Wrap Negative Offsets

Use div_euclid and rem_euclid when wraparound math must survive negative offsets: the remainder always lands in 0..divisor, unlike the built-in %.

RustData Integrity

Code

rustsnippet
17 lines
fn main() {
    let ring = ['a', 'b', 'c', 'd', 'e'];
    let len = ring.len() as i32;

    // 内置 %:符号跟随被除数,负偏移得到负索引,直接用会越界
    println!("-7 % 5 = {}", -7 % len);

    // rem_euclid:余数永远落在 0..除数,负偏移也能安全环绕
    for offset in [-7i32, -3, 0, 4, 9] {
        let idx = offset.rem_euclid(len);
        println!("offset {offset:+} -> index {idx} ({})", ring[idx as usize]);
    }

    // div_euclid 与 rem_euclid 满足恒等式 self = div*除数 + rem
    let (q, r) = ((-7).div_euclid(len), (-7).rem_euclid(len));
    println!("-7 = {q} * {len} + {r}");
}

Inside the snippet

div_euclid And rem_euclid Wrap Negative Offsets is built around the function main.

Repetition is confined to for offset in [-7i32, -3, 0, 4, 9] — the rest of the file is straight-line.

Using it

The demo output is labeled (-7 % 5 =, offset, -7 =), so every printed line maps back to its originating operation.

Key statements

let (q, r) = ((-7).div_euclid(len), (-7).rem_euclid(len));
let ring = ['a', 'b', 'c', 'd', 'e'];
let idx = offset.rem_euclid(len);

Interactive Tools for This Topic

FAQ

What does div_euclid And rem_euclid Wrap Negative Offsets print when run?
Invoke the file as-is — the `-7 % 5 =`, `offset`, `-7 =` prefixes identify which step printed each line.