TheAlgorithms/Go · error

strings must have a same length

Error message

strings must have a same length

What it means

hamming.Distance computes the Hamming distance, which is only defined for two strings of equal length. When the input strings differ in length the function cannot align them, so it returns -1 and this error.

Source

Thrown at strings/hamming/hammingdistance.go:20

This algorithm calculates the hamming distance between two equal length strings.
The Hamming distance between two equal-length strings of symbols is the number of positions
at which the corresponding symbols are different:
https://en.wikipedia.org/wiki/Hamming_distance

Note that we didn't consider strings as an array of bytes, therefore, we didn't use the XOR operator.
In this case, we used a simple loop to compare each character of the strings, and if they are different,
we increment the hamming distance by 1.

Parameters: two strings to compare
Output: distance between both strings */

package hamming

import "errors"

func Distance(str1, str2 string) (int, error) {
	if len(str1) != len(str2) {
		return -1, errors.New("strings must have a same length")
	}

	hammingDistance := 0
	for i := 0; i < len(str1); i++ {
		if str1[i] != str2[i] {
			hammingDistance++
		}
	}

	return hammingDistance, nil
}

View on GitHub (pinned to 5ba447ec5f)

Solutions

  1. Check that both strings have the same length before calling Distance
  2. Pad or trim the shorter string to match, if that is semantically valid for your data
  3. Use a different metric (e.g. Levenshtein distance) when inputs may legitimately differ in length

Example fix

// before
hamming.Distance("GATTACA", "GAT")
// after
if len(a) == len(b) { d, err := hamming.Distance(a, b) } else { /* handle mismatch */ }
Defensive patterns

Strategy: validation

Validate before calling

if len(str1) != len(str2) {
    return 0, fmt.Errorf("length mismatch: %d vs %d", len(str1), len(str2))
}
d, err := hamming.Distance(str1, str2)

Type guard

func sameLength(a, b string) bool { return len(a) == len(b) }

Try / catch

d, err := hamming.Distance(a, b)
if err != nil {
    if err.Error() == "strings must have a same length" {
        // handle length mismatch
    }
    return err
}

Prevention

When it happens

Trigger: Calling Distance(str1, str2) where len(str1) != len(str2), e.g. Distance('GATTACA', 'GATTACGA') or comparing strings of different byte lengths.

Common situations: Comparing DNA/rna sequences from sources with different trimming; comparing user-supplied strings without prior length normalization; accidentally comparing a string against its prefix or suffix.

Related errors


AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02). Data as JSON: /api/errors/4cab88e9b7612e3e. Report an issue: GitHub.