Reputation: 705
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
?
Upvotes: 5
Views: 1949
Reputation: 58735
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.
Upvotes: 10