Concept Flow - Accessing elements
Start
Create collection
Specify index/key
Access element
Use element (print, assign, etc.)
End
This flow shows how to access an element from a collection by specifying its index or key and then using that element.
let numbers = [10, 20, 30]; let first = numbers[0]; println!("{}", first);
| Step | Action | Expression | Result/Value |
|---|---|---|---|
| 1 | Create array | let numbers = [10, 20, 30]; | [10, 20, 30] |
| 2 | Access element at index 0 | numbers[0] | 10 |
| 3 | Assign to variable | let first = 10; | 10 |
| 4 | Print value | println!("{}", first); | Outputs: 10 |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| numbers | undefined | [10, 20, 30] | [10, 20, 30] | [10, 20, 30] | [10, 20, 30] |
| first | undefined | undefined | undefined | 10 | 10 |
Accessing elements in Rust: - Use square brackets [] with index to get element from array or vector. - Indexing starts at 0. - Example: let x = arr[0]; gets first element. - Accessing invalid index causes runtime panic. - Use the element by assigning or printing.
arr?arr[0] accesses the first element directly.v in Rust?v[2] to access the third element.let arr = [10, 20, 30, 40];
println!("{}", arr[1]);arr has elements: 10 at index 0, 20 at index 1, 30 at index 2, and 40 at index 3.arr[1], which is 20.let v = vec![1, 2, 3]; let x = v[3];
v has 3 elements at indexes 0, 1, and 2. Index 3 is out of range.v[3] causes a panic at runtime due to index out of bounds.let data = vec![vec![1, 2], vec![3, 4], vec![5, 6]];. How do you access the number 4?Pass the test and this pattern moves unknown