rust - rust 错误: value of type `std::vec::Vec<i32>` cannot be built from `std::iter::Iterator<Item=&i32>`

标签 rust reference

我是使用rust 的新手,遇到了错误

std::vec::Vec<i32> cannot be built from std::iter::Iterator<Item=&i32>


尝试使用函数get_even_numbers()通过按引用v而不是按值&v传递借入v时。
fn main() {
    let v: Vec<i32> = (0..10).collect();
    let even: Vec<i32> = get_even_numbers(&v);
    println!("Even numbers: {:?}", even);
}

fn get_even_numbers(v: &Vec<i32>) -> Vec<i32> {
    v.iter().filter(|x| x % 2 == 0).collect()
}
为何上面的代码会给出错误,但按值传递却没有,如下所示?
另外,我在通过引用传递时在函数内部使用了.iter(),而在通过值传递时在函数内部使用了.into_iter(),不确定是否这些是正确的函数。
fn main() {
    let v: Vec<i32> = (0..10).collect();
    let even: Vec<i32> = get_even_numbers(v);
    println!("Even numbers: {:?}", even);
}

fn get_even_numbers(v: Vec<i32>) -> Vec<i32> {
    v.into_iter().filter(|x| x % 2 == 0).collect()
}

// Even numbers: [0, 2, 4, 6, 8]

最佳答案

使用v.iter().filter(|x| x % 2 == 0).cloned().collect()。这将(平凡地)将每个&i32引用克隆为实际的i32值。

关于rust - rust 错误: value of type `std::vec::Vec<i32>` cannot be built from `std::iter::Iterator<Item=&i32>` ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64199782/

相关文章:

java - 是否可以获得对象引用计数?

closures - 如何返回一个通用的 Map 结构?

rust - 如何在编译时获取 const 的值?

C++ 通过引用传递——这可以做到吗?

c# - 如何在 foreach 循环中修改结构的属性?

perl - 如何直接取消引用存储在另一个哈希中的哈希引用?

c++ - 指针可以指向 cpu 寄存器吗?

rust - 更新非常旧的代码时出现问题

unit-testing - 有没有办法在 Rust 中构建测试以在不详尽时发出警告?

rust - 当我用rustc编译时,为什么会在Cargo.toml中被列为依赖项,所以会出现 “can' t find crate?