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 %.
Code
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
Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Text Wrap FormatterSoft-wrap paragraphs to a chosen column width for emails, commit messages, and terminal output, optionally breaking words longer than the width.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.