Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Vec have trait Sync?

According to the documentation, Vec<T> implements Sync if T implements Sync. It seems it's generated automatically by some magic, but I feel this is counter-intuitive since a naive implementation for vectors is not thread-safe.

Is Vec<T> in Rust really Sync?

like image 740
Remagpie Avatar asked Sep 01 '18 22:09

Remagpie


People also ask

What is VEC rust?

Vector is a module in Rust that provides the container space to store values. It is a contiguous resizable array type, with heap-allocated contents. It is denoted by Vec<T>. Vectors in Rust have O(1) indexing and push and pop operations in vector also take O(1) complexity.

What is sync rust?

Rust captures this through the Send and Sync traits. A type is Send if it is safe to send it to another thread. A type is Sync if it is safe to share between threads (T is Sync if and only if &T is Send).

What is send trait in Rust?

Send means that a type is safe to move from one thread to another. If the same type also implements Copy , this also means that it is safe to copy from one thread to another. Sync means that a type is safe to reference from multiple threads at the same time.

How do you initialize VEC in Rust?

In Rust, there are several ways to initialize a vector. In order to initialize a vector via the new() method call, we use the double colon operator: let mut vec = Vec::new();


1 Answers

Implementing Sync means that a type guarantees that references to its values can be shared between threads, without risk of a data race in safe Rust.

Values of type &Vec<T> are immutable, so it's always safe to share them. The Rust borrow checker already forbids a mutable reference to exist at the same time as any other reference to the same object so this works automatically as a result of Rust's borrowing rules. Nothing can mutate a Vec while it's shared, so a data race is impossible. Of course, if unsafe code comes into the picture then the guarantees are gone.

Most types are Sync in fact. The ones that aren't (for example RefCell) tend to have interior mutability, or otherwise manage references outside of the control of the compile-time borrow checker.

like image 86
Peter Hall Avatar answered Sep 19 '22 09:09

Peter Hall