我试图将 Vec 的引用缩减为其总和,以便计算其平均值。但是,我遇到了编译器问题,我不知道哪里出现了借用/引用错误。
// Given a list of integers, use a vector and return the mean (the average value), median (when sorted, the value in the middle position), and mode (the value that occurs most often; a hash map will be helpful here) of the list.
fn main() {
let list_of_integers = vec![200, -6_000, 3, 0, 23, 99, -1];
let mean_ans = mean(&list_of_integers);
// Other code that will also use list_of_integers hence why I want to reference list_of_integers so it doesn't get removed from memory
println!("mean is {}", mean_ans);
}
fn mean(integers: &Vec<i32>) -> i32 {
let length = integers.len() as i32;
let sum = integers.iter().reduce(|&a, &b| &(a + b));
match sum {
Some(v) => v / length,
None => 0,
}
}
当我运行cargo run时,我收到了一个编译器错误,rust-analyzer也将reduce方法中的&(a + b)标记为错误。下面是错误的文本,但我也附上了图片以清楚地显示它所引用的内容。
error[E0515]: cannot return reference to temporary value
--> src\main.rs:13:47
|
13 | let sum = integers.iter().reduce(|&a, &b| &(a + b));
| ^-------
| ||
| |temporary value created here
| returns a reference to data owned by the current function
error: aborting due to previous error
我不确定这里出了什么问题,因为我了解.iter()返回一个Vec的Iter引用,所以它的值已经被减小为&i32的a和b吗?当我从&(a + b)中删除&时,会得到以下编译器错误:“expected &i32
, found i32
help: consider borrowing here: &(a + b)
”。
请注意,我正在学习Rust,而且还没有完成其教程的一半,所以请随意将解决方案解释得像我是新手一样(因为我确实是新手)。
我使用的是Windows 10中的VSCode上的rust版本1.52.1和rustup版本1.24.1。
&(a + b)
毫无意义。 引用必须是对“某物”的引用,你正在返回对临时值的引用,这就像是一个局部变量,在闭包完成后被销毁。 请使用integers.iter().copied()
来获取数字上的迭代器而不是引用,并在两个地方删除&
。 - user4815162342