|
Size: 1241
Comment: Rewrite
|
← Revision 4 as of 2025-10-15 16:15:23 ⇥
Size: 975
Comment: Rewrite
|
| Deletions are marked like this. | Additions are marked like this. |
| Line 1: | Line 1: |
| ## page was renamed from Rust/ScopeAndMutability = Rust Scope and Mutability = |
= Rust Mutability = |
| Line 4: | Line 3: |
| Variables in Rust are available only in their immediate context. Most are also immutable. These defaults can be relaxed with keywords. | A description of '''mutability''' (and '''immutability''') in Rust. |
| Line 12: | Line 11: |
| == Mutability == | == Description == |
| Line 14: | Line 13: |
| Many variables are actually constant in Rust. To enable reassignment of a variable, it must be declared with the `mut` keyword. | Most variables are actually immutable by default. To ''enable'' mutability, a variable must be declared with the `mut` keyword. |
| Line 23: | Line 24: |
=== Shadowing === It is possible to shadow a variable, so as to allow re-use of a common name. |
It ''is'' possible to '''shadow''' a variable name, however. |
| Line 40: | Line 37: |
| == Scope == | == Tips == |
| Line 42: | Line 39: |
| === Global Variables === | === Global Scope === |
| Line 44: | Line 41: |
| Rust does not allow global variables. There are two options however for declaring a value in the global context: | Rust does not allow variables in the global scope. To place a value there, try: |
| Line 46: | Line 43: |
| 1. constants (i.e. `const THRESHOLD: i32 = 10`) 2. static variables |
1. declare a string literal (i.e. `const THRESHOLD: i32 = 10`) 2. use a function that returns a value given the `'static` reference lifetime |
| Line 49: | Line 46: |
| A static variable is simply a variable that's given the `'static` reference lifetime-it is kept for the entire lifecycle. Additionally, a `static` variable can only be declared with constant functions (i.e. declared with `const fn`) so that they can be computed at compile time. | {{{ fn coerce_static<'a>(_: &'a i32) -> &'a i32 { &NUM } |
| Line 51: | Line 51: |
| ---- == Unsafe == |
fn main() { let lifetime_num = 9; let coerced_static = coerce_static(&lifetime_num); } }}} |
Rust Mutability
A description of mutability (and immutability) in Rust.
Contents
Description
Most variables are actually immutable by default.
To enable mutability, a variable must be declared with the mut keyword.
fn main() {
let mut x = 0;
x = 1;
}It is possible to shadow a variable name, however.
fn main() {
let spaces = " ";
let spaces = spaces.len();
}
Tips
Global Scope
Rust does not allow variables in the global scope. To place a value there, try:
declare a string literal (i.e. const THRESHOLD: i32 = 10)
use a function that returns a value given the 'static reference lifetime
fn coerce_static<'a>(_: &'a i32) -> &'a i32 {
&NUM
}
fn main() {
let lifetime_num = 9;
let coerced_static = coerce_static(&lifetime_num);
}