1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Primitive traits and marker types representing basic 'kinds' of types.
13 //! Rust types can be classified in various useful ways according to
14 //! intrinsic properties of the type. These classifications, often called
15 //! 'kinds', are represented as traits.
17 //! They cannot be implemented by user code, but are instead implemented
18 //! by the compiler automatically for the types to which they apply.
20 //! Marker types are special types that are used with unsafe code to
21 //! inform the compiler of special constraints. Marker types should
22 //! only be needed when you are creating an abstraction that is
23 //! implemented using unsafe code. In that case, you may want to embed
24 //! some of the marker types below into your type.
30 /// Types able to be transferred across task boundaries.
31 #[unstable = "will be overhauled with new lifetime rules; see RFC 458"]
33 #[rustc_on_unimplemented = "`{Self}` cannot be sent between threads safely"]
34 pub unsafe trait Send: 'static {
38 /// Types with a constant size known at compile-time.
41 #[rustc_on_unimplemented = "`{Self}` does not have a constant size known at compile-time"]
46 /// Types that can be copied by simply copying bits (i.e. `memcpy`).
48 /// By default, variable bindings have 'move semantics.' In other
59 /// // `x` has moved into `y`, and so cannot be used
61 /// // println!("{:?}", x); // error: use of moved value
64 /// However, if a type implements `Copy`, it instead has 'copy semantics':
67 /// // we can just derive a `Copy` implementation
68 /// #[derive(Show, Copy)]
75 /// // `y` is a copy of `x`
77 /// println!("{:?}", x); // A-OK!
80 /// It's important to note that in these two examples, the only difference is if you are allowed to
81 /// access `x` after the assignment: a move is also a bitwise copy under the hood.
83 /// ## When can my type be `Copy`?
85 /// A type can implement `Copy` if all of its components implement `Copy`. For example, this
86 /// `struct` can be `Copy`:
95 /// A `struct` can be `Copy`, and `i32` is `Copy`, so therefore, `Point` is eligible to be `Copy`.
99 /// struct PointList {
100 /// points: Vec<Point>,
104 /// The `PointList` `struct` cannot implement `Copy`, because `Vec<T>` is not `Copy`. If we
105 /// attempt to derive a `Copy` implementation, we'll get an error.
108 /// error: the trait `Copy` may not be implemented for this type; field `points` does not implement
112 /// ## How can I implement `Copy`?
114 /// There are two ways to implement `Copy` on your type:
125 /// impl Copy for MyStruct {}
128 /// There is a small difference between the two: the `derive` strategy will also place a `Copy`
129 /// bound on type parameters, which isn't always desired.
131 /// ## When can my type _not_ be `Copy`?
133 /// Some types can't be copied safely. For example, copying `&mut T` would create an aliased
134 /// mutable reference, and copying `String` would result in two attempts to free the same buffer.
136 /// Generalizing the latter case, any type implementing `Drop` can't be `Copy`, because it's
137 /// managing some resource besides its own `size_of::<T>()` bytes.
139 /// ## When should my type be `Copy`?
141 /// Generally speaking, if your type _can_ implement `Copy`, it should. There's one important thing
142 /// to consider though: if you think your type may _not_ be able to implement `Copy` in the future,
143 /// then it might be prudent to not implement `Copy`. This is because removing `Copy` is a breaking
144 /// change: that second example would fail to compile if we made `Foo` non-`Copy`.
151 /// Types that can be safely shared between tasks when aliased.
153 /// The precise definition is: a type `T` is `Sync` if `&T` is
154 /// thread-safe. In other words, there is no possibility of data races
155 /// when passing `&T` references between tasks.
157 /// As one would expect, primitive types like `u8` and `f64` are all
158 /// `Sync`, and so are simple aggregate types containing them (like
159 /// tuples, structs and enums). More instances of basic `Sync` types
160 /// include "immutable" types like `&T` and those with simple
161 /// inherited mutability, such as `Box<T>`, `Vec<T>` and most other
162 /// collection types. (Generic parameters need to be `Sync` for their
163 /// container to be `Sync`.)
165 /// A somewhat surprising consequence of the definition is `&mut T` is
166 /// `Sync` (if `T` is `Sync`) even though it seems that it might
167 /// provide unsynchronised mutation. The trick is a mutable reference
168 /// stored in an aliasable reference (that is, `& &mut T`) becomes
169 /// read-only, as if it were a `& &T`, hence there is no risk of a data
172 /// Types that are not `Sync` are those that have "interior
173 /// mutability" in a non-thread-safe way, such as `Cell` and `RefCell`
174 /// in `std::cell`. These types allow for mutation of their contents
175 /// even when in an immutable, aliasable slot, e.g. the contents of
176 /// `&Cell<T>` can be `.set`, and do not ensure data races are
177 /// impossible, hence they cannot be `Sync`. A higher level example
178 /// of a non-`Sync` type is the reference counted pointer
179 /// `std::rc::Rc`, because any reference `&Rc<T>` can clone a new
180 /// reference, which modifies the reference counts in a non-atomic
183 /// For cases when one does need thread-safe interior mutability,
184 /// types like the atomics in `std::sync` and `Mutex` & `RWLock` in
185 /// the `sync` crate do ensure that any mutation cannot cause data
186 /// races. Hence these types are `Sync`.
188 /// Users writing their own types with interior mutability (or anything
189 /// else that is not thread-safe) should use the `NoSync` marker type
190 /// (from `std::marker`) to ensure that the compiler doesn't
191 /// consider the user-defined type to be `Sync`. Any types with
192 /// interior mutability must also use the `std::cell::UnsafeCell` wrapper
193 /// around the value(s) which can be mutated when behind a `&`
194 /// reference; not doing this is undefined behaviour (for example,
195 /// `transmute`-ing from `&T` to `&mut T` is illegal).
196 #[unstable = "will be overhauled with new lifetime rules; see RFC 458"]
198 #[rustc_on_unimplemented = "`{Self}` cannot be shared between threads safely"]
199 pub unsafe trait Sync {
204 /// A marker type whose type parameter `T` is considered to be
205 /// covariant with respect to the type itself. This is (typically)
206 /// used to indicate that an instance of the type `T` is being stored
207 /// into memory and read from, even though that may not be apparent.
209 /// For more information about variance, refer to this Wikipedia
210 /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
212 /// *Note:* It is very unusual to have to add a covariant constraint.
213 /// If you are not sure, you probably want to use `InvariantType`.
217 /// Given a struct `S` that includes a type parameter `T`
218 /// but does not actually *reference* that type parameter:
223 /// struct S<T> { x: *() }
224 /// fn get<T>(s: &S<T>) -> T {
226 /// let x: *T = mem::transmute(s.x);
232 /// The type system would currently infer that the value of
233 /// the type parameter `T` is irrelevant, and hence a `S<int>` is
234 /// a subtype of `S<Box<int>>` (or, for that matter, `S<U>` for
235 /// any `U`). But this is incorrect because `get()` converts the
236 /// `*()` into a `*T` and reads from it. Therefore, we should include the
237 /// a marker field `CovariantType<T>` to inform the type checker that
238 /// `S<T>` is a subtype of `S<U>` if `T` is a subtype of `U`
239 /// (for example, `S<&'static int>` is a subtype of `S<&'a int>`
240 /// for some lifetime `'a`, but not the other way around).
241 #[unstable = "likely to change with new variance strategy"]
242 #[lang="covariant_type"]
243 #[derive(PartialEq, Eq, PartialOrd, Ord)]
244 pub struct CovariantType<T: ?Sized>;
246 impl<T: ?Sized> Copy for CovariantType<T> {}
247 impl<T: ?Sized> Clone for CovariantType<T> {
248 fn clone(&self) -> CovariantType<T> { *self }
251 /// A marker type whose type parameter `T` is considered to be
252 /// contravariant with respect to the type itself. This is (typically)
253 /// used to indicate that an instance of the type `T` will be consumed
254 /// (but not read from), even though that may not be apparent.
256 /// For more information about variance, refer to this Wikipedia
257 /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
259 /// *Note:* It is very unusual to have to add a contravariant constraint.
260 /// If you are not sure, you probably want to use `InvariantType`.
264 /// Given a struct `S` that includes a type parameter `T`
265 /// but does not actually *reference* that type parameter:
270 /// struct S<T> { x: *const () }
271 /// fn get<T>(s: &S<T>, v: T) {
273 /// let x: fn(T) = mem::transmute(s.x);
279 /// The type system would currently infer that the value of
280 /// the type parameter `T` is irrelevant, and hence a `S<int>` is
281 /// a subtype of `S<Box<int>>` (or, for that matter, `S<U>` for
282 /// any `U`). But this is incorrect because `get()` converts the
283 /// `*()` into a `fn(T)` and then passes a value of type `T` to it.
285 /// Supplying a `ContravariantType` marker would correct the
286 /// problem, because it would mark `S` so that `S<T>` is only a
287 /// subtype of `S<U>` if `U` is a subtype of `T`; given that the
288 /// function requires arguments of type `T`, it must also accept
289 /// arguments of type `U`, hence such a conversion is safe.
290 #[unstable = "likely to change with new variance strategy"]
291 #[lang="contravariant_type"]
292 #[derive(PartialEq, Eq, PartialOrd, Ord)]
293 pub struct ContravariantType<T: ?Sized>;
295 impl<T: ?Sized> Copy for ContravariantType<T> {}
296 impl<T: ?Sized> Clone for ContravariantType<T> {
297 fn clone(&self) -> ContravariantType<T> { *self }
300 /// A marker type whose type parameter `T` is considered to be
301 /// invariant with respect to the type itself. This is (typically)
302 /// used to indicate that instances of the type `T` may be read or
303 /// written, even though that may not be apparent.
305 /// For more information about variance, refer to this Wikipedia
306 /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
310 /// The Cell type is an example which uses unsafe code to achieve
311 /// "interior" mutability:
314 /// struct Cell<T> { value: T }
317 /// The type system would infer that `value` is only read here and
318 /// never written, but in fact `Cell` uses unsafe code to achieve
319 /// interior mutability.
320 #[unstable = "likely to change with new variance strategy"]
321 #[lang="invariant_type"]
322 #[derive(PartialEq, Eq, PartialOrd, Ord)]
323 pub struct InvariantType<T: ?Sized>;
325 #[unstable = "likely to change with new variance strategy"]
326 impl<T: ?Sized> Copy for InvariantType<T> {}
327 #[unstable = "likely to change with new variance strategy"]
328 impl<T: ?Sized> Clone for InvariantType<T> {
329 fn clone(&self) -> InvariantType<T> { *self }
332 /// As `CovariantType`, but for lifetime parameters. Using
333 /// `CovariantLifetime<'a>` indicates that it is ok to substitute
334 /// a *longer* lifetime for `'a` than the one you originally
335 /// started with (e.g., you could convert any lifetime `'foo` to
336 /// `'static`). You almost certainly want `ContravariantLifetime`
337 /// instead, or possibly `InvariantLifetime`. The only case where
338 /// it would be appropriate is that you have a (type-casted, and
339 /// hence hidden from the type system) function pointer with a
340 /// signature like `fn(&'a T)` (and no other uses of `'a`). In
341 /// this case, it is ok to substitute a larger lifetime for `'a`
342 /// (e.g., `fn(&'static T)`), because the function is only
343 /// becoming more selective in terms of what it accepts as
346 /// For more information about variance, refer to this Wikipedia
347 /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
348 #[unstable = "likely to change with new variance strategy"]
349 #[lang="covariant_lifetime"]
350 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
351 pub struct CovariantLifetime<'a>;
353 /// As `ContravariantType`, but for lifetime parameters. Using
354 /// `ContravariantLifetime<'a>` indicates that it is ok to
355 /// substitute a *shorter* lifetime for `'a` than the one you
356 /// originally started with (e.g., you could convert `'static` to
357 /// any lifetime `'foo`). This is appropriate for cases where you
358 /// have an unsafe pointer that is actually a pointer into some
359 /// memory with lifetime `'a`, and thus you want to limit the
360 /// lifetime of your data structure to `'a`. An example of where
361 /// this is used is the iterator for vectors.
363 /// For more information about variance, refer to this Wikipedia
364 /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
365 #[unstable = "likely to change with new variance strategy"]
366 #[lang="contravariant_lifetime"]
367 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
368 pub struct ContravariantLifetime<'a>;
370 /// As `InvariantType`, but for lifetime parameters. Using
371 /// `InvariantLifetime<'a>` indicates that it is not ok to
372 /// substitute any other lifetime for `'a` besides its original
373 /// value. This is appropriate for cases where you have an unsafe
374 /// pointer that is actually a pointer into memory with lifetime `'a`,
375 /// and this pointer is itself stored in an inherently mutable
376 /// location (such as a `Cell`).
377 #[unstable = "likely to change with new variance strategy"]
378 #[lang="invariant_lifetime"]
379 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
380 pub struct InvariantLifetime<'a>;
382 /// A type which is considered "not POD", meaning that it is not
383 /// implicitly copyable. This is typically embedded in other types to
384 /// ensure that they are never copied, even if they lack a destructor.
385 #[unstable = "likely to change with new variance strategy"]
386 #[lang="no_copy_bound"]
387 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
388 #[allow(missing_copy_implementations)]
391 /// A type which is considered managed by the GC. This is typically
392 /// embedded in other types.
393 #[unstable = "likely to change with new variance strategy"]
394 #[lang="managed_bound"]
395 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
396 #[allow(missing_copy_implementations)]