Variables and constants

Note

When in doubt on variable type: just use i32 for everything! i32 is the default in Rust

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:

use itertools::Itertools;

fn main() {  
    let number_list = [1,12,3,1,5,2,7,8,7,8,2,3,12,7,7];
    let mode = number_list.iter().counts(); // Itertools::counts() 
    // возвращает Hashmap, где ключи взяты из массива, значения - частота
    for (key, value) in &mode {  
        println!("Число {key} встречается {value} раз");  
    }  }