CodeBlanks Logo Icon CodeBlanks

Comparing numbers

Parse the guess into a number and compare with Ordering.

Converting to a number

parse is used to turn text into a number; the target type must be given. The result is a Result because texts like "abc" can't be converted:

let tahmin: u32 = tahmin.trim().parse().expect("Bir sayı yaz!");

Here the old tahmin (a String) is shadowed by a new u32 with the same name; there's no need to invent another name.

cmp and Ordering

a.cmp(&b) returns one of three values of the type std::cmp::Ordering: Less, Greater, Equal. match forces you to handle all three:

use std::cmp::Ordering;

match tahmin.cmp(&gizli) {
    Ordering::Less => println!("Çok küçük"),
    Ordering::Greater => println!("Çok büyük"),
    Ordering::Equal => println!("Bildin!"),
}

If you forget an arm, the compiler gives a "non-exhaustive patterns" error.

Practice First comparison

Convert the text "30" with parse::<u32>() (unwrap) and compare it with let gizli: u32 = 42; using cmp. Print 30: Çok küçük for Less, Çok büyük for Greater and Bildin! for Equal.

Starter code

main.rs
use std::cmp::Ordering;

fn main() {
    // buraya yaz
}

Sample solution

main.rs
use std::cmp::Ordering;

fn main() {
    let gizli: u32 = 42;
    let tahmin: u32 = "30".parse().unwrap();
    match tahmin.cmp(&gizli) {
        Ordering::Less => println!("{}: Çok küçük", tahmin),
        Ordering::Greater => println!("{}: Çok büyük", tahmin),
        Ordering::Equal => println!("{}: Bildin!", tahmin),
    }
}

Expected output

30: Çok küçük

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does <code>"-5".parse::&lt;u32&gt;()</code> return?

  • Err(...) Correct answer
  • Ok(5)
  • Ok(-5)
  • Panic

Explanation: u32 is unsigned; the minus sign is an invalid digit and Err is returned.

2 Compare

Question
match tahmin.____(&gizli) {
    Ordering::Less => println!("Çok küçük"),
    Ordering::Greater => println!("Çok büyük"),
    Ordering::Equal => println!("Bildin!"),
}
Answer
match tahmin.cmp(&gizli) {
    Ordering::Less => println!("Çok küçük"),
    Ordering::Greater => println!("Çok büyük"),
    Ordering::Equal => println!("Bildin!"),
}

Explanation: cmp returns an Ordering value.

3 cmp result

Term Meaning
3.cmp(&5) Less
5.cmp(&3) Greater
5.cmp(&5) Equal
"x".parse::<u32>() Err

All lessons in Beginner