Rust 在 Vec 上的 Reduce 方法参考

问题描述 投票:0回答:2

我正在尝试将 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 引用,所以它的 a 和 b 的减少值不应该已经是 &i32 了吗?当我从 &(a + b) 中删除 & 时,出现以下编译器错误“预期

&i32
,发现
i32
帮助:考虑在这里借用:
&(a + b)
”。

注意,我刚刚学习 Rust,教程还不到一半,所以请随意解释解决方案,就像我是新手一样(因为我是新手)。

我在 Windows 10 的 VSCode 中使用 rust 版本 1.52.1 和 rustup 版本 1.24.1。

rust functional-programming reference rust-cargo borrow-checker
2个回答
12
投票

返回

&(a + b)
不起作用,因为它尝试返回对临时值的引用。
a + b
的结果的行为就像一个未命名的局部变量,即它是闭包的局部变量,并在返回之前被销毁。解决该问题的最优雅的方法是使用
integers.iter().copied()
来获取实际数字而不是引用的迭代器。这允许在两个地方省略
&

请注意,像

&(a + b)
这样的表达并不总是毫无意义。当您向下传递引用时,例如传递给需要引用的函数或运算符时,它非常有用。在这种情况下,例如
f(&(a + b))
{ let _tmp = a + b; f(&tmp) }
的简写,非常有意义。

与上述无关,您可能希望您的函数接受切片,

&[i32]
,而不是对向量的引用。这将在向量不变的情况下工作,并使您的函数接受其他连续的内存片段,例如来自数组。 (详情请参阅此处。)


4
投票

这里的问题是,传递给reduce的函数必须返回与原始迭代器项相同类型的值,对于通过

Iter
特征创建的迭代器来说,该值始终是
&T
。但是,您无法从函数返回引用,因为它会指向已释放的堆栈帧。
您的选择是:

  • 改为使用
    into_iter()
    ,它会消耗它所调用的集合并产生拥有的值,
  • 使用
    iter().cloned()
    它将克隆值,再次在拥有的值上生成一个迭代器,尽管这对于非原始类型来说可能成本高昂。

但是在求和迭代器的具体情况下,您应该只使用

iter().sum()

© www.soinside.com 2019 - 2024. All rights reserved.