Using a vector
The most basic collection is the vector, or Vec
for short. It is essentially a variable-length array with a very low overhead. As such, it is the collection that you will use most of the time.
How to do it...
- In the command line, jump one folder up with
cd ..
so you're not inchapter-one
anymore. In the next chapters, we are going to assume that you always started with this step. Create a Rust project to work on during this chapter with
cargo new chapter-two
.- Navigate into the newly-created
chapter-two
folder. For the rest of this chapter, we will assume that your command line is currently in this directory. - Inside the folder
src
, create a new folder calledbin
. - Delete the generated
lib.rs
file, as we are not creating a library. - In the folder
src/bin
, create a file calledvector.rs
. - Add the following code blocks to the file and run them with
cargo run --bin vector
:
1 fn main() { 2 // Create a vector with some elements 3 let fruits = vec!["apple", "tomato", "pear"]; 4 // A...