Is it possible to match float between value?

Hi !

I am learning rust. In the book, in the part 15.5, with the Listing 15-20 example, I want to test a match in place of the consecutive if...

I was thinking rust search for the first match that is ok with a condition, but it seems to not be possible to do that in this way...

Is there another way to match this part of code please ?

ORIGINAL CODE IN BOOK :

pub fn set_value(&mut self, value: usize) {
        self.value = value;

        let percentage_of_max = self.value as f64 / self.max as f64;

        if percentage_of_max >= 1.0 {
            self.messenger.send("Error: You are over your quota!");
        } else if percentage_of_max >= 0.9 {
            self.messenger
                .send("Urgent warning: You've used up over 90% of your quota!");
        } else if percentage_of_max >= 0.75 {
            self.messenger
                .send("Warning: You've used up over 75% of your quota!");
        }
    }

MY TENTATIVE :

pub fn set_value(&mut self, value:usize) {
    self.value = value;

    let percentage_of_max = self.value as f64 / self.max as f64;
    match percentage_of_max {
        (percentage_of_max >= 1.0) => self.messenger.send("Error: You are over your quota!"),
        percentage_of_max >= 0.9 => self.messenger.send("Urgent warning: You've used up over 90% of your quota!"),
        percentage_of_max >= 0.75 => self.messenger.send("Warning: You've used up over 75% of your quota!"),
    }
}

Thank you for your time. Have a nice day !

Use the conditionnal in the match, something like this:


fn main() {
    let value = 0.77;
    
    match value {
        val if value >= 1.0 => println!(">=1.0: {}",val),
        val if value >= 0.9 => println!(">=0.9: {}",val),
        val if value >= 0.75 => println!(">= 0.75: {}",val),
         _ => {}
    }
 }

Thank you very much lomac !

You can also use ranges:

fn main() {
    let value = 0.77;
    
    match value {
        1.0.. => println!(">=1.0: {}",value),
        0.9.. => println!(">=0.9: {}",value),
        0.75.. => println!(">= 0.75: {}",value),
        _ => {}
    }
 }
4 Likes