请考虑以下几点
use std::sync::{Arc,Mutex};
fn arc_mutex_from_slice<T>(v: &[T]) -> Arc<Mutex<[T]>> {
todo!();
}
fn main() {
let v = vec![1,2,3];
println!("{:#?}", arc_mutex_from_slice(&v[..]));
}
有没有可能实施arc_mutex_from_slice
?可以为Arc<Mutex<Box<[T]>>>
或Arc<Mutex<Vec<T>>>
实现此转换,但这两者都添加了另一个不必要的分配/间接.
类型Arc<Mutex<[T]>>
是有效的,并且可以在片的大小已知时被初始化.
let x = Arc::new(Mutex::new([1,2,3]));
但当切片的大小未知时,我找不到任何方法来实现这一点.天真地try 实现arc_mutex_from_slice
,如下所示不能编译.
fn arc_mutex_from_slice<T>(v: &[T]) -> Arc<Mutex<[T]>> {
return Arc::new(Mutex::new(*v));
}
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`
有哪unsafe
种魔法能帮上忙吗?