Convert &[T]/Vec<T> to Arc<Mutex<[T]>>? Possible?

Is it possible to create an Arc<Mutex<[T]>> from an unknown-sized slice &[T]?

Naively trying to implement arc_mutex_from_slice as follows does not compile:

fn arc_mutex_from_slice<T>(v: &[T]) -> Arc<Mutex<[T]>> {
    return Arc::new(Mutex::new(*v));
}

The compiler throws an error because the size of the slice is unknown at compile-time:

error[E0277]: the size for values of type `[T]` cannot be known at compilation time
 --> src/main.rs:4:21
  |
4 |     return Arc::new(Mutex::new(*v));
  |            -------- ^^^^^^^^^^^^^^ doesn't have a size known at compile-time
  |            |
  |            required by a bound introduced by this call
  |
  = help: within `Mutex<[T]>`, the trait `Sized` is not implemented for `[T]`
  = note: required because it appears within the type `Mutex<[T]>`
note: required by a bound in `Arc::<T>::new`

Is it possible to use unsafe to create an Arc<Mutex<[T]>> from an unknown-sized slice &[T]?

No, it is not possible to use unsafe to directly create an Arc<Mutex<[T]>> from an unknown-sized slice &[T]. The reason is that the size of the slice is not known at compile-time, and the Sized trait is not implemented for [T], which is required by Mutex<[T]>.

One possible solution is to use a Vec<T> instead of a slice, as Vec<T> has a known size at compile-time. You can convert the slice to a Vec<T> using the to_vec method, and then create the Arc<Mutex<Vec<T>>>:

use std::sync::{Arc, Mutex};

fn arc_mutex_from_slice<T>(v: &[T]) -> Arc<Mutex<Vec<T>>> {
    return Arc::new(Mutex::new(v.to_vec()));
}

This will compile successfully and allow you to create an Arc<Mutex<Vec<T>>> from the unknown-sized slice.