是否可以创建一个弧 [T] ?来自Vec T ? [英] Is it possible to create an Arc<[T]> from a Vec<T>?

查看:38
本文介绍了是否可以创建一个弧 [T] ?来自Vec T ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更具体地说,为什么没有 Arc 使用动态大小的 T 实现 from_rawBox ="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>对于 Rc<[T]>From>将添加 Rc.

还将为 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆