Tuples are a fixed size data structure that can accommodate a number of values of different types. it's size is however fixed at runtime.
let tup: (&str, i32) = ("obi", 24);
Tuple types are (type a, type b ...)
Similar to tuples, arrays are fixed in size, but can only accept values of the same type i.e Homogenous.
let arr: [i32, 5] = [1,2,3,4,5];
Array types are [type of data, length]
Vectors are dynamically size data structures that can grow or shrink and also Homogenous
There are several ways on how to declare a vector
// creates a vector from an array
let vec1 = vec![0,1,2,3,4];
// creates a new vector
let vec2 = Vec::new();
// creates a vector with capacity
let vec3 = Vec::<i32>::with_capacity();
vector types are Vec::<type of data>
The capacity of a vector is the amount of memory allocated to store its elements. it typically represents the amount of space the vector has reserved for future elements.
you can use methods push
and pop
for adding or removing data.
Each of the structures above can be stored in a specific memory slot. and references &
can point to their location in memory but not own it.
- Ordinary references points to a single value.
- Slice references points to a range of consecutive values.
giving the vector above: we can slice the index 0 - 4
let sv: &[i32] = &vec1[0..4]
// output: [0, 1, 2, 3]
strings are stored as a Vector
of bytes, they are growable, allocated in the heap, strictly a utf8 sequence and not null-terminated.
let str1 = String::from("peter"); // a string
let str2 = "peter".to_string(); // string too
let str3 = "peter" // a slice
let str4 = &str1; // also a slice