相关疑难解决方法(0)

为什么不鼓励接受对String(&String),Vec(&Vec)或Box(&Box)的引用作为函数参数?

我写了一些Rust代码&String作为参数:

fn awesome_greeting(name: &String) {
    println!("Wow, you are awesome, {}!", name);
}
Run Code Online (Sandbox Code Playgroud)

我还编写了代码来引用a VecBox:

fn total_price(prices: &Vec<i32>) -> i32 {
    prices.iter().sum()
}

fn is_even(value: &Box<i32>) -> bool {
    **value % 2 == 0
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到一些反馈意见,这样做并不是一个好主意.为什么不?

string reference rust borrowing

100
推荐指数
2
解决办法
5549
查看次数

如何编写一个带迭代器的Rust函数?

我想编写一个接受迭代器的函数,并返回一些操作的结果.具体来说,我试图迭代a的值HashMap:

use std::collections::HashMap;

fn find_min<'a>(vals: Iterator<Item=&'a u32>) -> Option<&'a u32> {
    vals.min()
}

fn main() {
    let mut map = HashMap::new();
    map.insert("zero", 0u32);
    map.insert("one", 1u32);
    println!("Min value {:?}", find_min(map.values()));
}
Run Code Online (Sandbox Code Playgroud)

可惜:

error: the `min` method cannot be invoked on a trait object
 --> src/main.rs:4:10
  |
4 |     vals.min()
  |          ^^^

error[E0277]: the trait bound `std::iter::Iterator<Item=&'a u32> + 'static: std::marker::Sized` is not satisfied
 --> src/main.rs:3:17
  |
3 | fn find_min<'a>(vals: Iterator<Item = &'a u32>) -> Option<&'a u32> {
  | …
Run Code Online (Sandbox Code Playgroud)

iterator function rust

51
推荐指数
3
解决办法
1万
查看次数

标签 统计

rust ×2

borrowing ×1

function ×1

iterator ×1

reference ×1

string ×1