Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the exclamation point mean in a trait implementation?

Tags:

I found in the library reference for std::rc::Rc this trait implementation

impl<T> !Send for Rc<T> 
where
    T: ?Sized, 

What does the exclamation point in front of Send mean?

I consulted both The Rust Programming Language¹ book and The Rust Reference², but didn't find an explanation. Please give a reference in your answer.


¹ especially the [section 3.19 Traits
² and sections 5.1 Traits and 5.1 Implementations
like image 974
nalply Avatar asked May 17 '15 19:05

nalply


People also ask

What does the exclamation point mean in Rust?

Rust is a curly-braces language with semicolons, C++-style comments and a main function - so far, so familiar. The exclamation mark indicates that this is a macro call.

What is the point of traits in Rust?

A trait tells the Rust compiler about functionality a particular type has and can share with other types. Traits are an abstract definition of shared behavior amongst different types. So, we can say that traits are to Rust what interfaces are to Java or abstract classes are to C++.

How do you implement a trait?

To implement a trait, declare an impl block for the type you want to implement the trait for. The syntax is impl <trait> for <type> . You'll need to implement all the methods that don't have default implementations. If your implementation is incomplete, your trusty friend the compiler will let you know.


2 Answers

It's a negative trait implementation for the Send trait as described in RFC 19.

As a summary: The Send trait is an auto trait, which means it is automatically implemented for all types that only contain other Send types:

unsafe auto trait Send {}

(Send is also an unsafe trait, which means it is unsafe to implement, but that is not relevant to the question.)

An auto trait may not define any methods, which also makes it a marker trait. (The syntax for defining auto traits is currently only available in the standard library or on the nightly compiler, but their semantics are stable.)

To opt out of the automatic implementation of Send, you must write an explicit negative trait implementation:

impl !Send for MyType {}

This means that even though MyType only contains other types that are Send, MyType itself will not automatically implement Send.

See also the answer to another question: What is an auto trait in Rust?

like image 143
8 revs, 5 users 54% Avatar answered Oct 27 '22 11:10

8 revs, 5 users 54%


This is a negative trait impl, so you can read it as opting out of the Send trait.

like image 43
fjh Avatar answered Oct 27 '22 10:10

fjh