find the first element in an array in rust

To find the first element in a Rust array, you can access the element at index 0 using square brackets [] notation.

Here's an example:

main.rs
let arr = [1, 2, 3];
let first_element = arr[0];
println!("The first element is: {}", first_element);
102 chars
4 lines

This code initializes an array with three elements [1, 2, 3]. Then, it assigns the first element of the array (1) to the first_element variable, and prints out the value. The output will be:

main.rs
The first element is: 1
24 chars
2 lines

If you want to find the first element of an array that is mutable (&mut), you can use the same syntax to mutate the element:

main.rs
let mut arr = [1, 2, 3];
arr[0] = 4;
println!("The first element is now: {}", arr[0]);
87 chars
4 lines

This code initializes a mutable array with three elements [1, 2, 3]. Then, it mutates the first element to be 4, and prints out the new value of the first element. The output will be:

main.rs
The first element is now: 4
28 chars
2 lines

related categories

gistlibby LogSnag