Problems about creating non Copy trait type array

For example, when i need to create a [String;N] -like array, just as

let a=[String::from("hello world");10];

the compiler would report that

the trait Copy is not implemented for String

but just with trait Clone, we could do in a proper way:

const DEFUALTSTRING:String = String::new();

pub fn buildarray<const N:usize>(val:String)->[String;N]{
    let mut a=[DEFUALTSTRING;N];
    for x in &mut a{
        x.clone_from(&val);
    }
    a
}

fn main(){
    let a:[String;10]=buildarray(String::from("hello world"));
}

so that we build the array a and take away the ownership of val at the same time

but it is not supported in default
and it costs one more time initialization for let mut a=[DEFUALTSTRING;N];

Another problem is that Default::default() is not a const fn

I don't not why it would be designed like this

Here's something I opened recently to add a function for it: Add `array::repeat` for making an array from a non-`Copy` non-`const` value · Issue #310 · rust-lang/libs-team · GitHub

For now, you can call array::from_fn(|_| String::from("hello world")) or ["hello world"; 10].map(String::from).

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.