Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reasoning behind marking a type that contains !Send fields with the Send trait?

Tags:

rust

What is the reasoning behind marking a type that contains !Send fields (like Rc or NonNull) with the Send trait? For instance, the standard library's LinkedList works in this fashion: it contains Option<NonNull<_>> fields and it implements Send trait (when T is Send).

How is this safe, what are the guarantees and ways to work safely with such a type?

like image 906
montekki Avatar asked Oct 22 '18 09:10

montekki


People also ask

Why is RC not send Rust?

The raw pointer types are not Send because Rust cannot make any guarantees about the synchronization mechanisms that are in the underlying types, or when the pointers will be accessed. Rc is not Send because it uses a non-atomic reference counter which is not safe to send between threads.

Does Rust support inheritance?

Inheritance as a Type System and as Code SharingIf a language must have inheritance to be an object-oriented language, then Rust is not. There is no way to define a struct that inherits the parent struct's fields and method implementations.

What is send in trait?

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.

What is send trait in 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).


1 Answers

Look at the rationale for NonNull being !Send:

NonNull pointers are not Send because the data they reference may be aliased.

But the NonNull in LinkedList is a private implementation detail. If this type knows that the inner type T is Send and the usage it does is also Send-safe, (no unsafety in the public API) then it can reintroduce the Send trait.

That guarantee basically winds down to ensuring that you cannot get mutable aliases to the inner types; and ensuring that there is no unexpected inner mutability (get a mutable reference from an immutable one).

These guarantees are not given by NonNull but they are in LinkedList.

like image 144
rodrigo Avatar answered Oct 07 '22 09:10

rodrigo