Luhn Checksum Walks Digits In Reverse

Walk digits in reverse, double every second one and fold 16 into 7, then the total must divide by ten for the card number to validate.

RustData Integrity

Code

rustsnippet
25 lines
// Luhn checksum walks the digits in reverse:validate card numbers 时
// 从最右位开始隔位翻倍,翻倍超过 9 就按位求和(等价于减 9)
fn luhn_check(digits: &str) -> bool {
    let sum: u32 = digits
        .chars()
        .rev()
        .enumerate()
        .map(|(i, c)| {
            let d = c.to_digit(10).expect("only digits");
            if i % 2 == 1 {
                let doubled = d * 2;
                if doubled > 9 { doubled - 9 } else { doubled }
            } else {
                d
            }
        })
        .sum();
    sum % 10 == 0
}

fn main() {
    // 经典样本:校验和为 70,能被 10 整除;末位改动一位立即失败
    println!("valid:   {}", luhn_check("79927398713"));
    println!("invalid: {}", luhn_check("79927398714"));
}

How it works

Luhn Checksum Walks Digits In Reverse is built around the functions luhn_check and main.

Applying it

The primary signature is fn luhn_check(digits: &str) -> bool

The run prints valid:, invalid: — each prefix names the step that produced it.

The entry point wires luhn_check together — run it once and the whole demo flows.

Statements that matter

.map(|(i, c)| {
    let d = c.to_digit(10).expect("only digits");
    if i % 2 == 1 {
        let doubled = d * 2;
        if doubled > 9 { doubled - 9 } else { doubled }
    } else {
        d
    }
})

Interactive Tools for This Topic

FAQ

What does Luhn Checksum Walks Digits In Reverse print when run?
No setup needed: run the file and look for labeled lines like `valid:`, `invalid:` in the output.