Nayuki
Nayuki

Reputation: 18552

How can I use the Ord::max function?

In this trivial program, I attempt to call i32.max(i32):

fn main() {
    let a: i32 = 0;
    let b: i32 = 1;
    let c: i32 = a.max(b);  // <-- Error here
    println!("{}", c);
}

But I get a cryptic compile-time error:

error: no method named `max` found for type `i32` in the current scope
 --> prog.rs:4:17
  |
4 |     let c: i32 = a.max(b);
  |                    ^^^
  |
  = note: the method `max` exists but the following
    trait bounds were not satisfied: `i32 : std::iter::Iterator`

Why does this happen? I'm using Rust 1.17.0.

How can I use the max() (or min()) function?

The example works if I use a floating point value:

let a: f32 = 0.0;
let b: f32 = 1.0;
let c: f32 = a.max(b);

This makes things more mysterious.

Upvotes: 2

Views: 1895

Answers (2)

DK.
DK.

Reputation: 59105

It works fine with a more recent compiler. You can see this by trying it on the playpen.

The problem is that you're trying to call a method that doesn't exist. At least, not in the version of Rust you're using. The documentation for Ord::max notes that it was introduced in Rust version 1.21.0.

What you want is to use cmp::max, which is a function, not a method. Thus, you call it like so:

use std::cmp;
let c = cmp::max(a, b);

As for why it works for f32, the answer to that can be found by checking the documentation: a search for max reveals that f32 and f64 have their own versions of a max method. And that's because both cmp::max and Ord::max only work on types that have a total ordering. Floats are not totally ordered due to the existence of NaN, so they cannot use either of those.

Upvotes: 6

bow
bow

Reputation: 2573

If you want to compare numbers, you'd do it like this:

use std::cmp;

fn main() {
    let a: i32 = 0;
    let b: i32 = 1;
    let c: i32 = cmp::max(a, b);
    println!("{}", c);
}

Upvotes: -2

Related Questions