我写了一些Rust代码&String作为参数:
fn awesome_greeting(name: &String) {
println!("Wow, you are awesome, {}!", name);
}
Run Code Online (Sandbox Code Playgroud)
我还编写了代码来引用a Vec或Box:
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)
但是,我收到一些反馈意见,这样做并不是一个好主意.为什么不?
这是我在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) 这段代码有什么问题?
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)