How to clone an array in Rust

1 Answer

0 votes
// A function that clones an array of any type T and any size N using const generics.
fn clone_my_array<T: Clone, const N: usize>(original: &[T; N]) -> [T; N] {
    // Calling .clone() on a reference to an array (&[T; N]) 
    // invokes the Clone implementation for arrays, deep-cloning each element.
    original.clone()
}

fn main() {
    // Example 1: Cloning an array of integers (which also implement Copy)
    let numbers = [1, 2, 3, 4, 5];
    let cloned_numbers = clone_my_array(&numbers);
    
    println!("Original: {:?}", numbers);
    println!("Cloned:   {:?}", cloned_numbers);

    // Example 2: Cloning an array of Strings (which implement Clone, but not Copy)
    let words = [String::from("rust"), String::from("safe"), String::from("fast")];
    let cloned_words = clone_my_array(&words);

    println!("Original words: {:?}", words);
    println!("Cloned words:   {:?}", cloned_words);
}


/*
run:

Original: [1, 2, 3, 4, 5]
Cloned:   [1, 2, 3, 4, 5]
Original words: ["rust", "safe", "fast"]
Cloned words:   ["rust", "safe", "fast"]

*/

 



answered 3 hours ago by avibootz
...