How to use a slice pattern to move elements out of an array in Rust

1 Answer

0 votes
/// Takes ownership of a 3-element array of strings and uses an array pattern 
/// to move the elements out by value, returning them individually in a tuple.
pub fn move_elements_out(arr: [String; 3]) -> (String, String, String) {
    // Destructuring the owned array by value moves each element out.
    // `first`, `second`, and `third` now own their respective Strings.
    // The array `arr` is fully consumed here.
    let [first, second, third] = arr;

    // Return the owned elements
    (first, second, third)
}

fn main() {
    // Create a stack-allocated array of Strings (Strings implement `Clone` and `Drop`, 
    // but not `Copy`, which forces a true ownership move).
    let word_array = [
        String::from("Alpha"),
        String::from("Beta"),
        String::from("Gamma"),
    ];

    println!("Moving elements out of the array...");

    // Pass the array by value, transferring ownership into the function
    let (w1, w2, w3) = move_elements_out(word_array);

    println!("Extracted Element 1: {}", w1);
    println!("Extracted Element 2: {}", w2);
    println!("Extracted Element 3: {}", w3);

    // -------------------------------------------------------------------------
    // COMPILE-TIME SAFETY CHECK:
    // If you uncomment the line below, the compiler will throw a 
    // "use of moved value: `word_array`" error because the array was consumed 
    // when its elements were moved out.
    // 
    // println!("{:?}", word_array);
    // -------------------------------------------------------------------------
}


/*
run:

Moving elements out of the array...
Extracted Element 1: Alpha
Extracted Element 2: Beta
Extracted Element 3: Gamma

*/

 



answered 1 day ago by avibootz
...