Vectors
Similar to array but can grow in size. Stored in the Heap
When creating an empty vector the type need to be specified
Elements in a Vector can be accessed directly using the Index but can lead to errors
Compiler will not detect this as Vector is dynamic object and is allocated on Heap. The invalid index access can only be detected at runtime
Values in the Vector can be modified by iterating over them using an mutable reference to the Vector and dereferencing (obtaining address) the current element
We can store data of multiple types in a Vector using Enums
To access values from the Vector we need to use the Match statement as depending on the datatype different operations can be performed on the underlying data
Strings
It is an collection of UTF-8 encoded characters. String is a wrapper over Vec<u8>
In UTF-8 characters can be represented using anywhere from 1 to 4 bytes
Since string as UTF-8 encoded even characters from other languages can be stored in them
Multiple strings can be joined together using the +
operator or using the format!()
macro
The below string contains 12 characters but requires 24 bytes to be stored in memory
Since different characters can have different lengths we cannot index into a string
Additionally, there are three relevant ways to look at a string. As bytes (u8
), scalar values (Rust char type representation) and grapheme clusters (Human characters)
While it is not possible to index over a String it is possible to create a string slice but since characters can be represented using different lengths the output could be different from what is expected
Storing UTF-8 Encoded Text with Strings - The Rust Programming Language
.bytes()
: Iterate over Bytes
.chars()
: Iterate over Rust Char represent of string
.graphemes(true)
: Iterate over graphemes (Import from unicode-segmentation
Crate)
HashMap
Used to represent Key Value pair data
If we pass a variable denoting a String as key the dictionary will get ownership of the value
For fetching a value and iteration we need to borrow the reference to the value
.or_insert()
methods returns an mutable reference to the value of the selected key. We can use this reference to modify the value