Variables and constants

Note

When in doubt on variable type: just use i32 for everything! i32 is the default in Rust, and the fastest, even on x64 architecture.

Scalar Types

Unsigned Signed
u8 i8
u16 i16
u32 i32
u64 i64
u128 i128
usize isize
Floating point vars: f32, f64.

You can declare number variables with _ sign in any place for convenience:

let x: i32 = 1_000_000;
let (mut missiles: i32, ready: u32) = (8, 5); // 2 vars tuple assign in 1 line

You can also add the var type to the number (convenient with _ when using generics):

let x = 1000_u32;
let y = 3.14_f32;

Converting

String2Int:

let n_str = "123456789".to_string();
let n_int = n_str.parse::<i32>().unwrap();

Char2Int:

let letter = 'a';
println!("{}", letter as u32 - 96); // = 97-96 = 1
let i = 97u8; // только с u8 разрешено делать 'as char'
println!("Value: {}", i as char);

Boolean type

bool type can be true or false. Non-integer - do NOT try to use arithmetic on these. But you can cast them:

true as u8;
false as u8;

Mutablitity

By default, variables in Rust are immutable. To make a variable mutable, special “mut” identifier must be placed. Rust compiler may infer the variable type from the type of value.

let x = 5; // immutable variable, type i32 guessed by Rust as default for numbers.

let mut x = 5; // mutable variable

Shadowing

Variable names can be reused. This is not mutability, because shadowing always re-creates the variable from scratch. Previous variable value may be used:

let x = 5; 
let x = x + 1; // new variable created with value = 6

Constants

Constant values are always immutable and available in the scope they were created in throughout the whole program. Type of constant must always be defined. Constants may contain results of operations. They are evaluated by Rust compiler. List of evaluations: https://doc.rust-lang.org/stable/reference/const_eval.html

const ONE_DAY_IN_SECONDS: u32 = 24 * 60 * 60; // type u32 MUST be defined

let phrase = "Hello World";
println!("Before: {phrase}"); // Before: Hello World

let phrase = phrase.len();
println!("After: {phrase}"); // After: 11

Compound variables

Tuple

Compound type, immutable, consists of different types.

let tup: (u32, f32, i32) = (10, 1.2, -32);
let (x,y,z) = tup; // tuple deconstructing into variables
let a1 = tup.0;
let a2 = tup.1; // another way to deconstruct values

Deconstructing tuples is very useful when a function returns a tuple:

let (left, right) = slice.split_at(middle);
let (_, right) = slice.split_at(middle); // use '_' to throw away part of return

Array

Compound type, mutable, all values of the same type.

let ar: [i32;5] = [1,2,3,4,5]; 
// array data is allocated on the stack rather than the heap
// [i32;5] - type of values and number of elements
let first = ar[0]; 
let second = ar[1]; // accessing array elements

Подсчёт одинаковых элементов в массиве с помощью itertools…