相关疑难解决方法(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
查看次数

在变量名之前和":"之后放置"mut"有什么区别?

这是我在Rust文档中看到的两个函数签名:

fn modify_foo(mut foo: Box<i32>) { *foo += 1; *foo }
fn modify_foo(foo: &mut i32) { *foo += 1; *foo }
Run Code Online (Sandbox Code Playgroud)

为什么不同的位置mut

似乎第一个函数也可以声明为

fn modify_foo(foo: mut Box<i32>) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

variables syntax reference mutable rust

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

在从引用中分配变量时,ref和&之间的区别是什么?

这段代码有什么问题?

fn example() {
    let vec = vec![1, 2, 3];
    let &_y = &vec;
}
Run Code Online (Sandbox Code Playgroud)
error[E0507]: cannot move out of borrowed content
 --> src/lib.rs:3:15
  |
3 |     let &_y = &vec;
  |         ---   ^^^^ cannot move out of borrowed content
  |         ||
  |         |data moved here
  |         help: consider removing the `&`: `_y`
  |
note: move occurs because `_y` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait
 --> src/lib.rs:3:10
  |
3 |     let &_y = &vec;
  |          ^^ …
Run Code Online (Sandbox Code Playgroud)

syntax reference pattern-matching rust

5
推荐指数
2
解决办法
625
查看次数