Is it possible to create Arc <[T]> from Vec <T>?

To be more specific, why not Arc<T> implement from_rawwith dynamic size T, but 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
}

( play )

As indicated in the comments, Arc::from_rawshould be used with a pointer from Arc::into_raw, so the above example does not make sense. My original question (is it possible to create Arc<[T]>from Vec<T>): is it possible, and if not, why?

+4
source share
3 answers

As with Rust 1.21.0, you can do this:

let thing: Arc<[i32]> = vec![1, 2, 3].into();

This was authorized by RFC 1845 :

, From<Vec<T>> for Rc<[T]> From<Box<T: ?Sized>> for Rc<T>.

API Arc.

copy_from_slice, Vec . , DK. .

+8

.

, , -. Arc::from_raw:

Arc::into_raw.

, unsafe.

-, , , . Vec<T>Box<[T]> , Vec<T> (Box<[T]>, usize). , Box<[T]> [1]. Arc<[T]>, , Box<[T]>, . , Arc<T>, , Box<T>.

Vec<T> Arc<[T]> - ... - . , - , , [2].

, , Arc::into_raw/Arc::from_raw . , Arc ... .


[1]: . Vec<T> Box<[T]> , - . , .

[2]: . , , Box<T> , , Vec<T>, Vec<T> Box, Vec ? " ArcVec<T>, ?" - .

+7

Arc<[T]> - Arc, T. [T] , , ( & [T], , , ).

use std::sync::Arc;

fn main() {
    let v: Vec<u32> = vec![1, 2, 3];
    let b: Box<[u32]> = v.into_boxed_slice();
    let y: Arc<[u32]> = Arc::new(*b);
    print!("{:?}", y)
}

Play Link

However, you can do Arc<&[T]>without creating an insert in the box:

use std::sync::Arc;

fn main() {
    let v = vec![1, 2, 3];
    let y: Arc<&[u32]> = Arc::new(&v[..]);
    print!("{:?}", y)
}

Shared Ref Play Link

However, this is similar to a study in a typical system with little practical value. If what you really want is a Vec view that you can get around between threads, Arc <& [T]> will give you what you want. And if you need it on the heap, Arc<Box<&[T]>>it works just fine too.

0
source

Source: https://habr.com/ru/post/1679654/


All Articles