相关疑难解决方法(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中的向量,切片或数组中交换项?

我的代码看起来像这样:

fn swap<T>(mut collection: Vec<T>, a: usize, b: usize) {
    let temp = collection[a];
    collection[a] = collection[b];
    collection[b] = temp;
}
Run Code Online (Sandbox Code Playgroud)

Rust非常肯定我不允许"脱离引用"或"移出索引内容",不管是什么.我如何说服Rust这是可能的?

rust

10
推荐指数
2
解决办法
5808
查看次数

标签 统计

rust ×2

borrowing ×1

reference ×1

string ×1