Rust variables: Difference between revisions
From wikinotes
Line 38: | Line 38: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- Mutability --> | </blockquote><!-- Mutability --> | ||
= Scope = | |||
<blockquote> | |||
Variable scope is bound to the block they are defined in <code>{ ... }</code>.<br> | |||
Blocks may be defined arbitrarily to create inner scopes.<br> | |||
Variables defined in outer scopes are accessible in inner scopes. | |||
<syntaxhighlight lang="rust"> | |||
fn foo() { | |||
let foo = 1; | |||
{ | |||
println!("{}", foo); | |||
} | |||
} | |||
</syntaxhighlight> | |||
</blockquote><!-- Scope --> | |||
= Introspection = | = Introspection = |
Revision as of 00:14, 7 September 2021
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;
Mutability
All variables are immutable by default in rust.
You can make them mutable with themut
modifier.let mut age: i8 = 30; age += 1;
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); } }
Introspection
TODO:
learn
// use std::any::type_name; (todo - learn)