Which value is smaller? Which is bigger? minimum and maximum in Rust

min max cmp

As I was trying to figure out how to get the minimum and maximum value from a vector I bumped into the min and max functions that work on two values and can tell use which is the smaller and which is the bigger value.

In this example you can see them working on integers and on strings.

examples/min-max/src/main.rs

fn main() {
    let x = 3;
    let y = 5;
    let min = std::cmp::min(x, y);
    println!("min: {}", min);

    let max = std::cmp::max(x, y);
    println!("max: {}", max);

    let x = "hello".to_string();
    let y = "world".to_string();

    let min = std::cmp::min(&x, &y);
    println!("min: {}", min);

    let max = std::cmp::max(x, y);
    println!("max: {}", max);
}

min: 3
max: 5
min: hello
max: world

Related Pages

Generic types for function parameters in Rust 🦀

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo