Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tutorial: documentation on mut #5721

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion doc/tutorial.md
Original file line number Diff line number Diff line change
Expand Up @@ -1067,6 +1067,28 @@ let mut d = @mut 5; // mutable variable, mutable box
d = @mut 15;
~~~~

A mutable variable and an immutable variable can refer to the same box, given
that their types are compatible. Mutability of a box is a property of its type,
however, so for example a mutable handle to an immutable box cannot be
assigned a reference to a mutable box.

~~~~
let a = @1; // immutable box
let b = @mut 2; // mutable box

let mut c : @int; // declare a variable with type managed immutable int
let mut d : @mut int; // and one of type managed mutable int

c = a; // box type is the same, okay
d = b; // box type is the same, okay
~~~~

~~~~ {.xfail-test}
// but b cannot be assigned to c, or a to d
c = b; // error
~~~~


# Move semantics

Rust uses a shallow copy for parameter passing, assignment and returning values
Expand All @@ -1081,6 +1103,16 @@ let y = x.clone(); // y is a newly allocated box
let z = x; // no new memory allocated, x can no longer be used
~~~~

Since in owned boxes mutability is a property of the owner, not the
box, mutable boxes may become immutable when they are moved, and vice-versa.

~~~~
let r = ~13;
let mut s = r; // box becomes mutable
*s += 1;
let t = s; // box becomes immutable
~~~~

# Borrowed pointers

Rust's borrowed pointers are a general purpose reference type. In contrast with
Expand Down Expand Up @@ -1191,7 +1223,7 @@ they are frozen:
let x = @mut 5;
let y = x;
{
let y = &*y; // the managed box is now frozen
let z = &*y; // the managed box is now frozen
// modifying it through x or y will cause a task failure
}
// the box is now unfrozen again
Expand Down