Rust study notes

Rust’s road from entry to abandonment!

ownership

transfer between variables

 1
2
3
4
 let s1 = String ::from( "hello" );
let s2 = s1; // move the value of s1 to s2
// ... so s2 is no longer valid here
println! ( "{}, world!" , s1); // here s1 no longer owns "hello"

When s1 is assigned to s2, Rust thinks that s1 is no longer valid, so there is no need to drop anything after s1 goes out of scope, which is to transfer ownership from s1 to s2, and s1 is invalid as soon as it is assigned to s2.

Since Rust prohibits you from using invalid references, you will see the following error:

 1
2
3
4
5
6
7
8
9
10
11
 error[E0382]: use of moved value: `s1`
--> src/main.rs:5:28
|
3 | let s2 = s1;
| -- value moved here
4 |
5 | println!("{}, world!", s1);
| ^^ value used here after move
|
= note: move occurs because `s1` has type `std::string::String`, which does
not implement the `Copy` trait

function transfer by value

 1
2
3
4
5
6
7
8
9
10
 fn main () {
let s = String ::from( "hello" ); // s goes into scope
takes_ownership(s); // the value of s is moved into the function...
// ... so no longer valid here
println! ( "{}" , s);
}

fn takes_ownership (x: String ) {
println! ( "{}" , x);
}
 1
2
3
4
5
6
7
8
9
10
 |
2 | let s = String::from("hello"); // s goes into scope
| - move occurs because `s` has type `String`, which does not implement the `Copy` trait
3 | takes_ownership(s); // The value of s is moved into the function...
| - value moved here
4 | // ... so no longer valid here
5 | println!("{}", s);
| ^ value borrowed here after move
|
= note: this error originates in the macro `$crate::format_args_nl` (in Nightly builds, run with -Z macro-backtrace for more info)

quote

Because of the default ownership transfer, a reference is needed when we only need a read-only variable and don’t want to transfer ownership.

Syntax: &s

 1
2
3
4
5
6
7
8
9
10
 fn main () {
let s = String ::from( "hello" ); // s goes into scope
takes_ownership(&s); // &s means read-only in takes_ownership and will not modify its value
// so this is no longer valid
println! ( "{}" , s);
}

fn takes_ownership (x: & String ) {
println! ( "{}" , x);
}

mutable reference

The referenced scope s starts at creation and lasts until it was last used

The scope of the variable lasts from creation to a certain curly brace }

 1
2
3
4
5
6
7
8
9
10
11
 fn main() {
let mut s = String::from("hello");

let r1 = &s;
let r2 = &s;
println!("{} and {}", r1, r2);
// In the new compiler, the r1, r2 scope ends here

let r3 = &mut s;
println!("{}", r3);
} // In the new compiler, the r3 scope ends here

This article is reprinted from: https://lvdawei.com/post/rust-note/
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment

Your email address will not be published.