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 pub unsafe trait Send: 'static {
37 /// Types with a constant size known at compile-time.
44 /// Types that can be copied by simply copying bits (i.e. `memcpy`).
46 /// By default, variable bindings have 'move semantics.' In other
57 /// // `x` has moved into `y`, and so cannot be used
59 /// // println!("{:?}", x); // error: use of moved value
62 /// However, if a type implements `Copy`, it instead has 'copy semantics':
65 /// // we can just derive a `Copy` implementation
66 /// #[derive(Show, Copy)]
73 /// // `y` is a copy of `x`
75 /// println!("{:?}", x); // A-OK!
78 /// It's important to note that in these two examples, the only difference is if you are allowed to
79 /// access `x` after the assignment: a move is also a bitwise copy under the hood.
81 /// ## When can my type be `Copy`?
83 /// A type can implement `Copy` if all of its components implement `Copy`. For example, this
84 /// `struct` can be `Copy`:
93 /// A `struct` can be `Copy`, and `i32` is `Copy`, so therefore, `Point` is eligible to be `Copy`.
97 /// struct PointList {
98 /// points: Vec<Point>,
102 /// The `PointList` `struct` cannot implement `Copy`, because `Vec<T>` is not `Copy`. If we
103 /// attempt to derive a `Copy` implementation, we'll get an error.
106 /// error: the trait `Copy` may not be implemented for this type; field `points` does not implement
110 /// ## How can I implement `Copy`?
112 /// There are two ways to implement `Copy` on your type:
123 /// impl Copy for MyStruct {}
126 /// There is a small difference between the two: the `derive` strategy will also place a `Copy`
127 /// bound on type parameters, which isn't always desired.
129 /// ## When can my type _not_ be `Copy`?
131 /// Some types can't be copied safely. For example, copying `&mut T` would create an aliased
132 /// mutable reference, and copying `String` would result in two attempts to free the same buffer.
134 /// Generalizing the latter case, any type implementing `Drop` can't be `Copy`, because it's
135 /// managing some resource besides its own `size_of::<T>()` bytes.
137 /// ## When should my type be `Copy`?
139 /// Generally speaking, if your type _can_ implement `Copy`, it should. There's one important thing
140 /// to consider though: if you think your type may _not_ be able to implement `Copy` in the future,
141 /// then it might be prudent to not implement `Copy`. This is because removing `Copy` is a breaking
142 /// change: that second example would fail to compile if we made `Foo` non-`Copy`.
149 /// Types that can be safely shared between tasks when aliased.
151 /// The precise definition is: a type `T` is `Sync` if `&T` is
152 /// thread-safe. In other words, there is no possibility of data races
153 /// when passing `&T` references between tasks.
155 /// As one would expect, primitive types like `u8` and `f64` are all
156 /// `Sync`, and so are simple aggregate types containing them (like
157 /// tuples, structs and enums). More instances of basic `Sync` types
158 /// include "immutable" types like `&T` and those with simple
159 /// inherited mutability, such as `Box<T>`, `Vec<T>` and most other
160 /// collection types. (Generic parameters need to be `Sync` for their
161 /// container to be `Sync`.)
163 /// A somewhat surprising consequence of the definition is `&mut T` is
164 /// `Sync` (if `T` is `Sync`) even though it seems that it might
165 /// provide unsynchronised mutation. The trick is a mutable reference
166 /// stored in an aliasable reference (that is, `& &mut T`) becomes
167 /// read-only, as if it were a `& &T`, hence there is no risk of a data
170 /// Types that are not `Sync` are those that have "interior
171 /// mutability" in a non-thread-safe way, such as `Cell` and `RefCell`
172 /// in `std::cell`. These types allow for mutation of their contents
173 /// even when in an immutable, aliasable slot, e.g. the contents of
174 /// `&Cell<T>` can be `.set`, and do not ensure data races are
175 /// impossible, hence they cannot be `Sync`. A higher level example
176 /// of a non-`Sync` type is the reference counted pointer
177 /// `std::rc::Rc`, because any reference `&Rc<T>` can clone a new
178 /// reference, which modifies the reference counts in a non-atomic
181 /// For cases when one does need thread-safe interior mutability,
182 /// types like the atomics in `std::sync` and `Mutex` & `RWLock` in
183 /// the `sync` crate do ensure that any mutation cannot cause data
184 /// races. Hence these types are `Sync`.
186 /// Users writing their own types with interior mutability (or anything
187 /// else that is not thread-safe) should use the `NoSync` marker type
188 /// (from `std::marker`) to ensure that the compiler doesn't
189 /// consider the user-defined type to be `Sync`. Any types with
190 /// interior mutability must also use the `std::cell::UnsafeCell` wrapper
191 /// around the value(s) which can be mutated when behind a `&`
192 /// reference; not doing this is undefined behaviour (for example,
193 /// `transmute`-ing from `&T` to `&mut T` is illegal).
194 #[unstable = "will be overhauled with new lifetime rules; see RFC 458"]
196 pub unsafe trait Sync {
201 /// A marker type whose type parameter `T` is considered to be
202 /// covariant with respect to the type itself. This is (typically)
203 /// used to indicate that an instance of the type `T` is being stored
204 /// into memory and read from, even though that may not be apparent.
206 /// For more information about variance, refer to this Wikipedia
207 /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
209 /// *Note:* It is very unusual to have to add a covariant constraint.
210 /// If you are not sure, you probably want to use `InvariantType`.
214 /// Given a struct `S` that includes a type parameter `T`
215 /// but does not actually *reference* that type parameter:
220 /// struct S<T> { x: *() }
221 /// fn get<T>(s: &S<T>) -> T {
223 /// let x: *T = mem::transmute(s.x);
229 /// The type system would currently infer that the value of
230 /// the type parameter `T` is irrelevant, and hence a `S<int>` is
231 /// a subtype of `S<Box<int>>` (or, for that matter, `S<U>` for
232 /// any `U`). But this is incorrect because `get()` converts the
233 /// `*()` into a `*T` and reads from it. Therefore, we should include the
234 /// a marker field `CovariantType<T>` to inform the type checker that
235 /// `S<T>` is a subtype of `S<U>` if `T` is a subtype of `U`
236 /// (for example, `S<&'static int>` is a subtype of `S<&'a int>`
237 /// for some lifetime `'a`, but not the other way around).
238 #[unstable = "likely to change with new variance strategy"]
239 #[lang="covariant_type"]
240 #[derive(PartialEq, Eq, PartialOrd, Ord)]
241 pub struct CovariantType<T: ?Sized>;
243 impl<T: ?Sized> Copy for CovariantType<T> {}
244 impl<T: ?Sized> Clone for CovariantType<T> {
245 fn clone(&self) -> CovariantType<T> { *self }
248 /// A marker type whose type parameter `T` is considered to be
249 /// contravariant with respect to the type itself. This is (typically)
250 /// used to indicate that an instance of the type `T` will be consumed
251 /// (but not read from), even though that may not be apparent.
253 /// For more information about variance, refer to this Wikipedia
254 /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
256 /// *Note:* It is very unusual to have to add a contravariant constraint.
257 /// If you are not sure, you probably want to use `InvariantType`.
261 /// Given a struct `S` that includes a type parameter `T`
262 /// but does not actually *reference* that type parameter:
267 /// struct S<T> { x: *const () }
268 /// fn get<T>(s: &S<T>, v: T) {
270 /// let x: fn(T) = mem::transmute(s.x);
276 /// The type system would currently infer that the value of
277 /// the type parameter `T` is irrelevant, and hence a `S<int>` is
278 /// a subtype of `S<Box<int>>` (or, for that matter, `S<U>` for
279 /// any `U`). But this is incorrect because `get()` converts the
280 /// `*()` into a `fn(T)` and then passes a value of type `T` to it.
282 /// Supplying a `ContravariantType` marker would correct the
283 /// problem, because it would mark `S` so that `S<T>` is only a
284 /// subtype of `S<U>` if `U` is a subtype of `T`; given that the
285 /// function requires arguments of type `T`, it must also accept
286 /// arguments of type `U`, hence such a conversion is safe.
287 #[unstable = "likely to change with new variance strategy"]
288 #[lang="contravariant_type"]
289 #[derive(PartialEq, Eq, PartialOrd, Ord)]
290 pub struct ContravariantType<T: ?Sized>;
292 impl<T: ?Sized> Copy for ContravariantType<T> {}
293 impl<T: ?Sized> Clone for ContravariantType<T> {
294 fn clone(&self) -> ContravariantType<T> { *self }
297 /// A marker type whose type parameter `T` is considered to be
298 /// invariant with respect to the type itself. This is (typically)
299 /// used to indicate that instances of the type `T` may be read or
300 /// written, even though that may not be apparent.
302 /// For more information about variance, refer to this Wikipedia
303 /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
307 /// The Cell type is an example which uses unsafe code to achieve
308 /// "interior" mutability:
311 /// struct Cell<T> { value: T }
314 /// The type system would infer that `value` is only read here and
315 /// never written, but in fact `Cell` uses unsafe code to achieve
316 /// interior mutability.
317 #[unstable = "likely to change with new variance strategy"]
318 #[lang="invariant_type"]
319 #[derive(PartialEq, Eq, PartialOrd, Ord)]
320 pub struct InvariantType<T: ?Sized>;
322 #[unstable = "likely to change with new variance strategy"]
323 impl<T: ?Sized> Copy for InvariantType<T> {}
324 #[unstable = "likely to change with new variance strategy"]
325 impl<T: ?Sized> Clone for InvariantType<T> {
326 fn clone(&self) -> InvariantType<T> { *self }
329 /// As `CovariantType`, but for lifetime parameters. Using
330 /// `CovariantLifetime<'a>` indicates that it is ok to substitute
331 /// a *longer* lifetime for `'a` than the one you originally
332 /// started with (e.g., you could convert any lifetime `'foo` to
333 /// `'static`). You almost certainly want `ContravariantLifetime`
334 /// instead, or possibly `InvariantLifetime`. The only case where
335 /// it would be appropriate is that you have a (type-casted, and
336 /// hence hidden from the type system) function pointer with a
337 /// signature like `fn(&'a T)` (and no other uses of `'a`). In
338 /// this case, it is ok to substitute a larger lifetime for `'a`
339 /// (e.g., `fn(&'static T)`), because the function is only
340 /// becoming more selective in terms of what it accepts as
343 /// For more information about variance, refer to this Wikipedia
344 /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
345 #[unstable = "likely to change with new variance strategy"]
346 #[lang="covariant_lifetime"]
347 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
348 pub struct CovariantLifetime<'a>;
350 /// As `ContravariantType`, but for lifetime parameters. Using
351 /// `ContravariantLifetime<'a>` indicates that it is ok to
352 /// substitute a *shorter* lifetime for `'a` than the one you
353 /// originally started with (e.g., you could convert `'static` to
354 /// any lifetime `'foo`). This is appropriate for cases where you
355 /// have an unsafe pointer that is actually a pointer into some
356 /// memory with lifetime `'a`, and thus you want to limit the
357 /// lifetime of your data structure to `'a`. An example of where
358 /// this is used is the iterator for vectors.
360 /// For more information about variance, refer to this Wikipedia
361 /// article <http://en.wikipedia.org/wiki/Variance_%28computer_science%29>.
362 #[unstable = "likely to change with new variance strategy"]
363 #[lang="contravariant_lifetime"]
364 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
365 pub struct ContravariantLifetime<'a>;
367 /// As `InvariantType`, but for lifetime parameters. Using
368 /// `InvariantLifetime<'a>` indicates that it is not ok to
369 /// substitute any other lifetime for `'a` besides its original
370 /// value. This is appropriate for cases where you have an unsafe
371 /// pointer that is actually a pointer into memory with lifetime `'a`,
372 /// and this pointer is itself stored in an inherently mutable
373 /// location (such as a `Cell`).
374 #[unstable = "likely to change with new variance strategy"]
375 #[lang="invariant_lifetime"]
376 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
377 pub struct InvariantLifetime<'a>;
379 /// A type which is considered "not POD", meaning that it is not
380 /// implicitly copyable. This is typically embedded in other types to
381 /// ensure that they are never copied, even if they lack a destructor.
382 #[unstable = "likely to change with new variance strategy"]
383 #[lang="no_copy_bound"]
384 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
385 #[allow(missing_copy_implementations)]
388 /// A type which is considered managed by the GC. This is typically
389 /// embedded in other types.
390 #[unstable = "likely to change with new variance strategy"]
391 #[lang="managed_bound"]
392 #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
393 #[allow(missing_copy_implementations)]