- Implicit definition
let a = 10;
- Explicit definition
let a:i32 = 10;
- Scalar
- Numeric
- Integer
- Fixed Size Types
i8
i16
i32
i64
u8
u16
u32
u64
- Variable Size Types
The integer type in which the particular size depends on the underlying machine architecture.
isize
The pointer-sized signed integer type.usize
The pointer-sized unsigned integer type.
- Fixed Size Types
- Float
f32
single-precisionf64
double-precision floating-point.
- Integer
- Non-Numeric
- Boolean
true/false
- Character
let ch:char ='a'; // single quotes
let st:&str = "Rust Programming"; // double quotes
string is any sequence of characters enclosed within double quotes.
- Boolean
- Numeric
- Compound
- Array
- homogenous sequence of elements
- By default, arrays are immutable.
- An array can only be of a fixed length
- By default, the first element is always at index 0.
- declare an array
let arr:[i32; 4] = [1, 2, 3, 4];
- Access an element in an array
arr[0]
- making an array mutable
let mut arr:[i32;4] = [1, 2, 3, 4];
- print a full array using debug trait.
println!("Array: {:?}", arr);
- get length of the array.
arr.len();
- Slice is basically a portion of an array.
- Size of the slice is unknown at compile time.
- Slice is a two-word object, 1st word is data-pointer & 2nd word is slice length.
let _slice:&[i32] = &arr[1..3];
- Tuple
- heterogeneous sequences of elements
- tuples are of fixed length.
let data : (&str, &str, i32) = ("Alice", "Lavine", 32);
- access the value of the tuple
data.1
- making tuples mutable
let mut data : (&str, &str, i32) = ("Alice", "Lavine", 32)
- print tuple
println!("Tuple - Data : {:?}", data)
- getting length of the tuple is not possible, unlike
array.len()
.
- Array
const
keyword to be used.- Constant variables are ones that are declared constant throughout the program scope, meaning, their value cannot be modified.
- They can be defined in global and local scope.
const ID: u32 = 6767;
- Differences between const and let variables.
- Scope:
const
variables can be declared in global and local scope, unlikelet
variables that are declared only in the local scope. - Mutability:
const
variable cannot be mutable unlikelet
which can be made mutable usingmut
keyword. - Data-type: Unlike
let
variables, it is mandatory to define the data type ofconst
variables. - Set Value at Runtime: The value of
const
variable can only be set before running the program whereas thelet
variable can store the result at runtime. - Shadowing: Unlike
let
variables,const
variables cannot be shadowed.
- Scope: