3.1 Vector for Algorithms in Rust
3 Basic Vector Algorithm Problems in Rust
Full Course on Data Structures and Algorithms in Rust
By: Chrysanthus Date Published: 3 Feb 2026
The reader is advised to read all the lessons (tutorials) in this full course, in the order presented.
An vector is a list structure that can be used to store many items in one place. In Rust, the items have to be of the same type. Imagine that there is a list of items; for example, a shopping list. The items are listed in one column or in one row on a paper. Such a column or row is conceptually similar to an vector. Similarly, if air temperatures for each day in a locality, are planned to be recorded over the next 365 days, then all the temperatures would be recorded in one vector. The vector will have 365 data entries.
Creating an Vector
One way to create an vector is as shown in the following program:
fn main() {
let vtr = ["bread", "butter", "cheese"];
}
The first and last code segments must be there. The single middle code segment of one statement is what creates the vector. It begins with the data type of the elements for the vector. In this case, the data type is a string, which should have been included among the pre-processing directives. arr is the name of the vector and should be followed by the square brackets, to indicate that the variable is an vector. Each shopping item is in a pair of double quotes. These quotes are not the word processor quotes; they are quotes of the text editor. The items are separated by commas. There is no comma after the last item. The vector literal or initializer_list is delimited by braces (curly brackets). This is separated from the left hand side of the statement, by the assignment operator (=).
The first three lines of the program, have to be there. These are pre-processing directives. The first line include the stdio.h library for input and output (keyboard/terminal). The next line includes the string library, for the string class (data type). The third line used, insists that any namespace used, is of the standard namespace. The fourth line, creates the vector, with the vector literal on the right of the assignment (=) operator. This has the shopping items as strings. The last code segment is the Rust main function, which has to be there. This function in its current form, has the minimum of its coding. Note the function parameters and the return statement, that have to be there.
The statement (fourth) above that creates the vector, is both a declaration and a definition. It is a definition because of the initializer_list (vector literal). A declaration is a definition, but a definition is not necessarily a declaration. A definition is an optional sub-part of a declaration, that puts items in memory.
A vector can be declared as a simple declaration, without the vector literal. In this case it is not really a definition. Also, the number of vector items must be included in the square brackets, when it is not a definition. If 3 items are to be in the vector, then the simple creation statement would be:
let mut vtr = Vec::with_capacity(3);
In theory, this created vector is empty.
Giving an Vector, Elements
When an vector is created with the initializer_list, the elements (values) are already given. If the vector is created with just a simple declaration and not effectively defined, then the vector values have to be given, for the different elements as follows:
fn main() {
let mut vtr: Vec<&str> = Vec::new(); // Create empty vector
vtr.push("bread"); // Index 0
vtr.push("butter"); // Index 1
vtr.push("cheese"); // Index 2
}
An vector can be seen as different variables next to one another, but with the same name. The actual different variables are differentiated by indexes. Index counting begins from 0, and not 1. The index for a particular value is in square brackets, just after the vector name.
Note that though the simple declaration has been made outside of the Rust main() function, the assignment of the values have been made inside the Rust main() function. Assignment of any value is not allowed outside any function, in Rust .
Accessing Vector Values
Vector values in Rust can only be read one-by-one. This is done using the subscript notation (index in square brackets). The syntax is:
let mut variable = Vec::with_capacity(length);
The following code segment will output "butter" after the vector has been created:
let var = vtr[1];
println!("{}", var);
This code segment should be in the Rust main() function or in any other function, below the creation of the vector (with values given). The printf statement sends the value of var to the terminal (screen) and then sends the cursor (I-bar, flashing) to the next line below, at the output.
It has been explained above, how to set (give) value to an vector element.
Modifying an Vector
The elements of a Rust vector can only be modified, one-by-one. The subscript notation is still used. The syntax is:
vector_name[index] = value;
The value has to be of the same type as all the vector elements. The following code segment will output "chocolate paste" instead of "cheese", after the above vector has been created:
vtr[2] = "chocolate paste";
println!("{}", vtr[2]);
The output is "chocolate paste". This code segment has to be in the Rust main() function or in any other function, below the creation of the vector (with values given).
The index corresponding to the vector value "cheese" is 2. "cheese" was replaced.
In Rust, once an vector has been created, its length cannot be changed. This means that a new item cannot be added after the last item of the vector.
The length of an vector can also not be reduced, once created.
Iterating over an Vector
The do-while-loop
The following program, shows a do-while-loop in Rust :
fn main() {
let vtr = ["bread", "butter", "cheese"];
let mut i = 0;
'r#do: loop {
println!("{}", vtr[i]);
i = i + 1; // increment: add 1
if !(i < 3) {
break 'r#do;
}
}
}
Note that the do-while-loop is in the Rust main() function and not outside of any function. The vector is not declared (and defined) inside any function. It could still have been defined inside the Rust main() function or any other function.
The output consists of each of the vector elements, beginning from the first, then second and then third.
The do-while-loop has a block, delimited by curly brackets (braces). The "do" reserved word is in front of this block. The loop uses a variable, i that is incremented for each pass, through the block.
The statements in the block are executed over and over, in the order typed. The while-condition is that, the block should stop executing, when the value of i is just below 3, that is 2. The first statement in the block prints out an vector value. The second statement increments i (adds 1). The block is executed 3 times; when i is 0; i is 1; and i is 2. i was initialized to 1, in front of the do-while-loop.
With the do-while-loop, the block is executed before the while-condition is checked. Note that the do-while-loop construct ends with a semicolon, just after the while-condition "(i<3)".
The While-Loop
The while-loop is similar to the do-while-loop. With the while-loop, the while-condition is checked before the loop body (block) is executed, for each iteration. With the do-while-loop above, the body is executed first, before the while-condition is checked, for each iteration. The following while-loop code segment would replace the above do-while-loop code segment (would do the same thing):
fn main() {
let vtr = ["bread", "butter", "cheese"];
let mut i = 0;
while i < 3 {
println!("{}", vtr[i]);
i += 1; //increment: add 1
}
}
Note that the while-loop construct does not end with a semicolon after, '}'. Also note the alternative increment statement, "i += 1;", which is the same as "i = i + 1;"
The for-Loop
The while-loop has a difference with the do-while-loop. The for-loop is another way of coding the while-loop. The above while-loop code segment would be coded with the for-loop as follows:
fn main() {
let vtr = ["bread", "butter", "cheese"];
for i in 0..3 {
println!("{}", vtr[i]);
}
}
The for-loop begins with the reserved word, "for" with all letters in lowercase. Then there is the parentheses. In the parentheses, there are three statements, with the last one not ending with a semicolon. The last statement is the increment statement, which has been transferred from the body of the while-loop, to this position. The middle statement is the while-condition. The first statement is the initialization of i to 0; it is no longer outside the construct. There is now only one statement in the body of this loop (for-loop). The output here, is the same as in the previous cases.
Conclusion
An vector can be created as the following two code segments show:
let mut vtr = ["bread", "butter", "cheese"];
let mut vtr = Vec::with_capacity(3);
vtr.push("bread"); // Index 0
vtr.push("butter"); // Index 1
vtr.push("cheese"); // Index 2
The vector can be handled with subscripts (index in square brackets).
Related Links
More Related LinksCousins
BACK NEXTComments
Note: You can use the Search Box above to find articles and discussions of interest.