add an element to the end of an array in rust

To add an element to the end of an array in Rust, you can use the push method of a mutable array. Here's an example:

main.rs
fn main() {
    let mut arr = [1, 2, 3];

    arr.push(4);

    println!("{:?}", arr);
}
89 chars
8 lines

In this example, we create an array arr with initial elements [1, 2, 3]. The array is mutable, as indicated by the mut keyword in the declaration. We then call the push method on the array, passing in the element we want to add to the end (in this case, 4).

The push method modifies the array in place, adding the new element to the end. We can then print out the updated array using the println! macro and the {:?} formatting specifier. The output will be:

main.rs
[1, 2, 3, 4]
13 chars
2 lines

Note that you cannot use push on a fixed-size array, as the size of the array is determined at compile time and cannot be changed at runtime. If you need to add elements to a collection that can grow or shrink dynamically, you may want to consider using a Vec.

gistlibby LogSnag