Validate Numbers With Luhn Checksum

The Luhn checksum doubles every second digit from the right, folds two-digit products, and accepts the number only when the total divides by ten.

GoData Integrity

Code

gosnippet
38 lines
package main

import (
	"fmt"
	"strconv"
	"strings"
)

// luhn: double every second digit from the right; subtract 9 when the doubled value exceeds 9
func luhnValid(number string) bool {
	number = strings.ReplaceAll(number, " ", "")
	if len(number) < 2 {
		return false
	}
	sum := 0
	double := false
	for i := len(number) - 1; i >= 0; i-- {
		digit, err := strconv.Atoi(string(number[i]))
		if err != nil {
			return false
		}
		if double {
			digit *= 2
			if digit > 9 {
				digit -= 9
			}
		}
		sum += digit
		double = !double
	}
	return sum%10 == 0
}

func main() {
	for _, number := range []string{"4539 1488 0343 6467", "4539 1488 0343 6468", "1234"} {
		fmt.Println(number, "->", luhnValid(number))
	}
}

What the code does

What another module actually calls is the functions luhnValid and main — everything else is wiring.

The loop for i := len(number) - 1; i >= 0; i-- is the only repeated construct. Error handling is inline: 1 place test err != nil and branch immediately.

Watch out for

  • Nothing sits in the dependency list; the runtime itself supplies it all.

Applying it

The primary signature, spelled out, is func luhnValid(number string) bool

The demo flow inside main is luhnValid — run the file to see it end to end.

Statements that matter most here

for _, number := range []string{"4539 1488 0343 6467", "4539 1488 0343 6468", "1234"} {
	fmt.Println(number, "->", luhnValid(number))
}
if err != nil {
	return false
}
return sum%10 == 0

Interactive Tools for This Topic

FAQ

How do you run Validate Numbers With Luhn Checksum?
Run the file on its own; every call resolves against the standard surface it already imports.