是否可以创建一个弧 [T] ?来自Vec T ? [英] Is it possible to create an Arc<[T]> from a Vec<T>?
问题描述
更具体地说,为什么没有 Arc
使用动态大小的 T
实现 from_raw
而 Box
="https://doc.rust-lang.org/std/boxed/struct.Box.html#method.from_raw" rel="noreferrer">是否?
To be more specific, why doesn't Arc<T>
implement from_raw
with a dynamically sized T
while Box<T>
does?
use std::sync::Arc;
fn main() {
let x = vec![1, 2, 3].into_boxed_slice();
let y = Box::into_raw(x);
let z = unsafe { Arc::from_raw(y) }; // ERROR
}
(播放)
正如评论中所指出的,Arc::from_raw
必须与来自Arc::into_raw
的指针一起使用,所以上面的例子没有意义.我最初的问题(是否可以从 Vec
创建Arc<[T]>
)仍然存在:这可能吗,如果没有,为什么?
As pointed out in the comments, Arc::from_raw
must be used with a pointer from Arc::into_raw
, so the above example doesn't make sense. My original question (Is it possible to create an Arc<[T]>
from a Vec<T>
) remains: is this possible, and if not, why?
推荐答案
从 Rust 1.21.0 开始,你可以这样做:
As of Rust 1.21.0, you can do this:
let thing: Arc<[i32]> = vec![1, 2, 3].into();
这是由 RFC 1845 启用的:
另外:From
和 From
.
还将为 Arc
添加相同的 API.
Identical APIs will also be added for Arc
.
在内部,这个使用一个方法称为copy_from_slice
,所以Vec
的分配没有被重用.有关原因的详细信息,请查看 DK. 的答案.
Internally, this uses a method called copy_from_slice
, so the allocation of the Vec
is not reused. For the details why, check out DK.'s answer.
这篇关于是否可以创建一个弧 [T] ?来自Vec T ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!