i32
&
: shared reference&mut
: mutable reference'static
.https://doc.rust-lang.org/rust-by-example/flow_control/match/destructuring/destructure_pointers.html
x
: &x
rf
: *rf
See:
{:b} |
binary |
{:o} |
octal |
{:x} |
hexadecimal (lowercase) |
{:X} |
hexadecimal (uppercase) |
{:?} |
for debugging |
{} |
user friendly |
Copy
traits.
Copy
and Clone
traits are similar but have different purposes.https://doc.rust-lang.org/rust-by-example/scope/move.html
Drop
trait (to drop ownership)
Drop::drop()
can't be called manually.Box
Box
has move semantics by default.
This works:
fn foo () {
let x = Box::new(5);
println!("x is: {}", x);
}
fn main() {
;
foo()}
/*
$ rustc hello.rs && ./hello
x is: 5
*/
This works too:
fn foo (x: Box<i32>) {
println!("x is: {}", x);
}
fn main() {
let x = Box::new(5);
foo(x);
//println!("x is: {}", x);
}
But this doesn't:
fn foo (x: Box<i32>) {
println!("x is: {}", x);
}
fn main() {
let x = Box::new(5);
// ownership of x 'moves' to foo. main no longer owns x
;
foo(x)
// main is trying to use something it doesn't own. Error!
println!("x is: {}", x);
}
Error is:
error[E0382]: borrow of moved value: `x`
--> hello.rs:9:24
|
7 | let x = Box::new(5);
| - move occurs because `x` has type `Box<i32>`, which does not implement the `Copy` trait
8 | foo(x);
| - value moved here
9 | println!("x is: {}", x);
| ^ value borrowed here after move
|
note: consider changing this parameter type in function `foo` to borrow instead if owning the value isn't necessary
--> hello.rs:2:12
|
2 | fn foo (x: Box<i32>) {
| --- ^^^^^^^^ this parameter takes ownership of the value
| |
| in this function
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider cloning the value if the performance cost is acceptable
|
8 | foo(x.clone());
| ++++++++
error: aborting due to previous error
For more information about this error, try `rustc --explain E0382`.
# --bin for binary program (--lib for library)
# initializes a git repo by default. Disabling with --vcs none
cargo new <proj_name> --bin --vcs none