gpt4 book ai didi

compiler-errors - 如何使用 Ord::max 函数?

转载 作者:行者123 更新时间:2023-11-29 08:07:44 24 4
gpt4 key购买 nike

在这个简单的程序中,我尝试调用 i32.max(i32):

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

但是我得到了一个神秘的编译时错误:

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`

为什么会这样?我正在使用 Rust 1.17.0。

如何使用 max() (或 min() )函数?

如果我使用浮点值,则该示例有效:

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

这让事情变得更加神秘。

最佳答案

它适用于较新的编译器。你可以通过trying it on the playpen看到这个.

问题是您正在尝试调用不存在 的方法。至少,不是在您使用的 Rust 版本中。 documentation for Ord::max注意到它是在 Rust 版本 1.21.0 中引入的。

你想要的是使用cmp::max ,这是一个函数,不是方法。因此,您可以这样调用它:

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

至于为什么它适用于f32,可以通过查看文档找到答案:a search for max表明 f32f64 有它们自己的 max 方法版本。 那是,因为cmp::maxOrd::max 仅适用于具有总排序的类型。由于 NaN 的存在, float 不是完全有序的,因此它们不能使用其中任何一个。

关于compiler-errors - 如何使用 Ord::max 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47130574/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com