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

Viewed 75

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?

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.

Related