Start learning free

LESSON 203 OF 293 · PROJECTS: EVERYDAY PROGRAMS

Password Strength V6 in Rust: A 0 to 100 Score

Practice Read the full explanation

Combine the earlier checks into a single numeric score between 0 and 100.

You start with:

The Rust editor starts empty, so write the whole program yourself. Begin with the data:

let mut password = "Secret!99";

Build:

Length: 9
Score: 100

Rules:

  • Start with score = 0.
  • If the length is at least 8, add 25.
  • If the password contains an uppercase letter, add 20.
  • If it contains a lowercase letter, add 20.
  • If it contains a digit, add 20.
  • If it contains a symbol (not a letter and not a digit), add 15.
  • Print "Length: " followed by the length, then print "Score: " followed by the score.

Try other passwords: with abc123 the output is

Length: 6
Score: 40

Use the same char methods, then accumulate into a mutable integer score.

let mut password = "Secret!99";
let mut length = password.len();
let mut hasUpper = false;
let mut hasLower = false;
let mut has_digit = false;
let mut hasSymbol = false;
for c in password.chars() {
    if c.is_uppercase() {
        hasUpper = true;
    }
    if c.is_lowercase() {
        hasLower = true;
    }
    if c.is_ascii_digit() {
        has_digit = true;
    }
    if !c.is_alphanumeric() {
        hasSymbol = true;
    }
}
let mut score = 0;
if length >= 8 {
    score += 25;
}
if hasUpper {
    score += 20;
}
if hasLower {
    score += 20;
}
if has_digit {
    score += 20;
}
if hasSymbol {
    score += 15;
}
println!("Length: {}", length);
println!("Score: {}", score);

STEP 1 OF 19
    Ctrl + Enter to check

    RUST · PROJECTS: EVERYDAY PROGRAMS

    Password Strength V6 in Rust, explained

    Problem overview

    Version 6 combines the character checks into one number. The score starts at 0 and gains points for each property of the password:

    • 25 for a length of at least 8;
    • 20 for an uppercase letter;
    • 20 for a lowercase letter;
    • 20 for a digit;
    • 15 for a symbol, meaning a character that is neither a letter nor a digit.

    The maximum is 25 + 20 + 20 + 20 + 15 = 100. For Secret!99 the program prints:

    Length: 9
    Score: 100
    

    For abc123 it prints Length: 6 and Score: 40: a lowercase letter and a digit, 20 each, and nothing else.

    Approach: collect facts, then add up points

    The program separates two jobs. First a loop over the characters sets four flags: has an uppercase letter, has a lowercase letter, has a digit, has a symbol. Then a series of independent if statements adds each rule's points to score. Each rule is its own if, never an else if, because a password can earn several awards at once. Keeping the scan and the scoring apart makes each easy to change on its own.

    Step by step

    1. Create password with the text "Secret!99".
    2. Create length from password.len().
    3. Create the four flags, hasUpper, hasLower, has_digit and hasSymbol, each with let mut and false.
    4. Loop with for c in password.chars().
    5. Test uppercase with c.is_uppercase(), and set hasUpper.
    6. Test lowercase with c.is_lowercase(), and set hasLower.
    7. Test digit with c.is_ascii_digit(), and set has_digit.
    8. Test symbol with !c.is_alphanumeric(), and set hasSymbol.
    9. Create score with let mut, set to 0.
    10. Add 25 if length >= 8.
    11. Add 20 for each of hasUpper, hasLower and has_digit, and add 15 for hasSymbol, each in its own if.
    12. Print the Length line, then the Score line.

    The solution in Rust

            let mut password = "Secret!99";
            let mut length = password.len();
            let mut hasUpper = false;
            let mut hasLower = false;
            let mut has_digit = false;
            let mut hasSymbol = false;
            for c in password.chars() {
                if c.is_uppercase() {
                    hasUpper = true;
                }
                if c.is_lowercase() {
                    hasLower = true;
                }
                if c.is_ascii_digit() {
                    has_digit = true;
                }
                if !c.is_alphanumeric() {
                    hasSymbol = true;
                }
            }
            let mut score = 0;
            if length >= 8 {
                score += 25;
            }
            if hasUpper {
                score += 20;
            }
            if hasLower {
                score += 20;
            }
            if has_digit {
                score += 20;
            }
            if hasSymbol {
                score += 15;
            }
            println!("Length: {}", length);
            println!("Score: {}", score);
    

    Rust details worth knowing:

    • Unicode-aware tests. This version uses is_uppercase(), is_lowercase() and is_alphanumeric(), which understand letters beyond ASCII. The digit test is still is_ascii_digit(). So É counts as uppercase, and é as a letter rather than a symbol. For Sécret!99 the score is 100, with the é counted as a lowercase letter and the ! as the only symbol.
    • Bytes versus characters. len() counts bytes, so é adds 2 to the length. Sécret!99 prints Length: 10 although it has 9 characters.
    • The compiler's warnings. Names such as hasUpper compile, but rustc warns variable `hasUpper` should have a snake case name and suggests has_upper, the usual Rust style. The mut on password and length is also unnecessary, because neither changes, and rustc says variable does not need to be mutable. They are warnings only, so the program builds and runs.
    • score is an i32. The literals 25, 20 and 15 add to it with +=, and 100 fits easily.
    • The flags are checked directly. if hasUpper needs no comparison.

    Tracing the score

    For abc123 the loop sets the lowercase and digit flags, so the four flags end as false, true, true and false. Then the rules run in order, and only the ones whose condition holds add points:

    lower -> 20
    digit -> 40
    score 40
    

    The length rule does not fire, because the length is 6, and neither do the uppercase and symbol rules. Each if is tested independently, so the order of the rules does not change the final sum.

    The same score with any

    The flags are only used to feed the points. Iterator methods can skip them:

    let mut score = 0;
    if password.len() >= 8 { score += 25; }
    if password.chars().any(|c| c.is_uppercase()) { score += 20; }
    if password.chars().any(|c| c.is_lowercase()) { score += 20; }
    if password.chars().any(|c| c.is_ascii_digit()) { score += 20; }
    if password.chars().any(|c| !c.is_alphanumeric()) { score += 15; }
    

    For Secret!99 this also gives 100. It scans the text once per rule instead of once in total. The lesson's version, with one loop and four flags, shows the scan and the scoring as two separate jobs.

    The compiler error for a missing mut

    Forgetting mut is the most common slip in this kind of program. Declaring let score = 0; and then writing score += 25; in an if fails to compile, with this message:

    error[E0384]: cannot assign twice to immutable variable `score`
    

    The compiler's own suggestion is to write let mut score = 0;. The same applies to every counter and flag in this project: a variable that changes inside a loop needs mut, and one that never changes does not.

    Why the weights add up to 100

    The point values are a design choice, not a Rust rule: 25 for length, 20 for each of three character classes and 15 for symbols, so a password that passes everything lands on exactly 100. Because every rule is an independent if, changing a weight means editing one number, and adding a rule means adding one more if. The score can never go above 100 or below 0 here, since it only ever grows from 0 by those five amounts.

    Edge cases and common mistakes

    • Using else if for the rules. Only the first matching award would be added, and the score would stall.
    • Length alone. 12345678 scores 45: 25 for length plus 20 for a digit. abcdefgh and ABCDEFGH also score 45.
    • Short and varied. abc123 scores 40 despite being short, because the length points are the only ones it misses.
    • Empty password. The score is 0.
    • Printing before scoring. The Score line must come after the if statements, or it shows 0.
    • Test choice. is_ascii_digit() keeps digits to 0 to 9; is_numeric() would also accept digits from other scripts.

    Testing

    PasswordLengthScore
    Secret!999100
    abc123640
    abcdefgh845
    ABCDEFGH845
    12345678845
    Sécret!9910100
    (empty)00
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free