Rust variables: Difference between revisions
From wikinotes
No edit summary |
|||
Line 52: | Line 52: | ||
</blockquote><!-- Scope --> | </blockquote><!-- Scope --> | ||
= Mutability = | = Mutability and Freezing = | ||
<blockquote> | <blockquote> | ||
All variables are immutable by default in rust.<br> | All variables are immutable by default in rust.<br> | ||
Line 63: | Line 63: | ||
You can bind mutable variables as immutable within inner scopes.<br> | You can bind mutable variables as immutable within inner scopes.<br> | ||
This will prevent them from being modified within that scope. | This will prevent them from being modified within that scope.<br> | ||
This is known as ''freezing'' a variable. | |||
<syntaxhighlight lang="rust"> | <syntaxhighlight lang="rust"> | ||
let mut age: i8 = 30; | let mut age: i8 = 30; |
Revision as of 00:26, 7 September 2021
Declaration
You may declare variables in rust, but it is not necessary.
let foo: u8;
Assignment
let age: u8 = 200; // typed let age = 200u8; // type-suffix let age = 200; // implied type
Literals
Literal types can be declared without assigning a type.
let float = 3.14; // f64 let integer = 7; // i32
Constants
Constants can be declared in any scope (including global).
constants cannot be changed once assigned.const SALT: &str = "$6$r1ohStL5/UwpNnls"; static RETRIES: i8 = 5;
Scope
Variable scope is bound to the block they are defined in
{ ... }
.
Blocks may be defined arbitrarily to create inner scopes.
Variables defined in outer scopes are accessible in inner scopes.fn foo() { let foo = 1; { println!("{}", foo); } }
Mutability and Freezing
All variables are immutable by default in rust.
You can make them mutable with themut
modifier.let mut age: i8 = 30; age += 1;You can bind mutable variables as immutable within inner scopes.
This will prevent them from being modified within that scope.
This is known as freezing a variable.let mut age: i8 = 30; { let age = age; // immutable until block scope ends }
Introspection
TODO:
learn
// use std::any::type_name; (todo - learn)