実体・参照のメソッド呼び出しは同じ.
でできる
let bmi1 = body.bmi_calc();
let bmi2 = (&body).bmi_calc();
ベクタの値を走査する時にベクタに参照(&
)を使う理由は、所有権の移動が発生し、走査して以降ベクタが利用できなくなるからである。
参照を使わずに所有権の移動する例
let v = vec![100, 32, 57];
for i in v {
println!("{}", i);
}
for i in v {
println!("{}", i);
}
error[E0382]: use of moved value: `v`
--> src\main.rs:8:10
|
3 | let v = vec![100, 32, 57];
| - move occurs because `v` has type `Vec<i32>`, which does not implement the `Copy` trait
4 | for i in v {
| -
| |
| `v` moved due to this implicit call to `.into_iter()`
| help: consider borrowing to avoid moving into the for loop: `&v`
...
8 | for i in v {
| ^ value used here after move
|
実体・参照のメソッド呼び出しは同じ.
でできる
let bmi1 = body.bmi_calc();
let bmi2 = (&body).bmi_calc();
fn main() {
let reference_to_nothing = dangle();
}
fn dangle() -> &String {
let s = String::from("hello");
&s
}
error[E0106]: missing lifetime specifier
--> src\main.rs:5:16
|
5 | fn dangle() -> &String {
| ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime
|
5 | fn dangle() -> &'static String {
| ~~~~~~~~
fn main() {
let s = String::from("hello");
change(&s);
}
fn change(some_string: &String) {
some_string.push_str(", world");
/*
error[E0596]: cannot borrow `*some_string` as mutable, as it is behind a `&` reference
--> src\main.rs:7:5
|
6 | fn change(some_string: &String) {
| ------- help: consider changing this to be a mutable reference: `&mut String`
7 | some_string.push_str(", world");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `some_string` is a `&` reference, so the data it refers to cannot be borrowed as mutable
*/
}