]> git.lizzy.rs Git - rust.git/blob - src/libstd/primitive_docs.rs
e6e6be2e45379a9ab39b9188fac28ef114433d3e
[rust.git] / src / libstd / primitive_docs.rs
1 // Copyright 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.
4 //
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.
10
11 #[doc(primitive = "bool")]
12 //
13 /// The boolean type.
14 ///
15 /// The `bool` represents a value, which could only be either `true` or `false`. If you cast
16 /// a `bool` into an integer, `true` will be 1 and `false` will be 0.
17 ///
18 /// # Basic usage
19 ///
20 /// `bool` implements various traits, such as [`BitAnd`], [`BitOr`], [`Not`], etc.,
21 /// which allow us to perform boolean operations using `&`, `|` and `!`.
22 ///
23 /// [`if`] always demands a `bool` value. [`assert!`], being an important macro in testing,
24 /// checks whether an expression returns `true`.
25 ///
26 /// ```
27 /// let bool_val = true & false | false;
28 /// assert!(!bool_val);
29 /// ```
30 ///
31 /// [`assert!`]: macro.assert.html
32 /// [`if`]: ../book/first-edition/if.html
33 /// [`BitAnd`]: ops/trait.BitAnd.html
34 /// [`BitOr`]: ops/trait.BitOr.html
35 /// [`Not`]: ops/trait.Not.html
36 ///
37 /// # Examples
38 ///
39 /// A trivial example of the usage of `bool`,
40 ///
41 /// ```
42 /// let praise_the_borrow_checker = true;
43 ///
44 /// // using the `if` conditional
45 /// if praise_the_borrow_checker {
46 ///     println!("oh, yeah!");
47 /// } else {
48 ///     println!("what?!!");
49 /// }
50 ///
51 /// // ... or, a match pattern
52 /// match praise_the_borrow_checker {
53 ///     true => println!("keep praising!"),
54 ///     false => println!("you should praise!"),
55 /// }
56 /// ```
57 ///
58 /// Also, since `bool` implements the [`Copy`](marker/trait.Copy.html) trait, we don't
59 /// have to worry about the move semantics (just like the integer and float primitives).
60 ///
61 /// Now an example of `bool` cast to integer type:
62 ///
63 /// ```
64 /// assert_eq!(true as i32, 1);
65 /// assert_eq!(false as i32, 0);
66 /// ```
67 #[stable(feature = "rust1", since = "1.0.0")]
68 mod prim_bool { }
69
70 #[doc(primitive = "never")]
71 //
72 /// The `!` type, also called "never".
73 ///
74 /// `!` represents the type of computations which never resolve to any value at all. For example,
75 /// the [`exit`] function `fn exit(code: i32) -> !` exits the process without ever returning, and
76 /// so returns `!`.
77 ///
78 /// `break`, `continue` and `return` expressions also have type `!`. For example we are allowed to
79 /// write:
80 ///
81 /// ```
82 /// # fn foo() -> u32 {
83 /// let x: ! = {
84 ///     return 123
85 /// };
86 /// # }
87 /// ```
88 ///
89 /// Although the `let` is pointless here, it illustrates the meaning of `!`. Since `x` is never
90 /// assigned a value (because `return` returns from the entire function), `x` can be given type
91 /// `!`. We could also replace `return 123` with a `panic!` or a never-ending `loop` and this code
92 /// would still be valid.
93 ///
94 /// A more realistic usage of `!` is in this code:
95 ///
96 /// ```
97 /// # fn get_a_number() -> Option<u32> { None }
98 /// # loop {
99 /// let num: u32 = match get_a_number() {
100 ///     Some(num) => num,
101 ///     None => break,
102 /// };
103 /// # }
104 /// ```
105 ///
106 /// Both match arms must produce values of type [`u32`], but since `break` never produces a value
107 /// at all we know it can never produce a value which isn't a [`u32`]. This illustrates another
108 /// behaviour of the `!` type - expressions with type `!` will coerce into any other type.
109 ///
110 /// [`u32`]: primitive.str.html
111 /// [`exit`]: process/fn.exit.html
112 ///
113 /// # `!` and generics
114 ///
115 /// The main place you'll see `!` used explicitly is in generic code. Consider the [`FromStr`]
116 /// trait:
117 ///
118 /// ```
119 /// trait FromStr: Sized {
120 ///     type Err;
121 ///     fn from_str(s: &str) -> Result<Self, Self::Err>;
122 /// }
123 /// ```
124 ///
125 /// When implementing this trait for [`String`] we need to pick a type for [`Err`]. And since
126 /// converting a string into a string will never result in an error, the appropriate type is `!`.
127 /// (Currently the type actually used is an enum with no variants, though this is only because `!`
128 /// was added to Rust at a later date and it may change in the future). With an [`Err`] type of
129 /// `!`, if we have to call [`String::from_str`] for some reason the result will be a
130 /// [`Result<String, !>`] which we can unpack like this:
131 ///
132 /// ```ignore (string-from-str-error-type-is-not-never-yet)
133 /// #[feature(exhaustive_patterns)]
134 /// // NOTE: This does not work today!
135 /// let Ok(s) = String::from_str("hello");
136 /// ```
137 ///
138 /// Since the [`Err`] variant contains a `!`, it can never occur. If the `exhaustive_patterns`
139 /// feature is present this means we can exhaustively match on [`Result<T, !>`] by just taking the
140 /// [`Ok`] variant. This illustrates another behaviour of `!` - it can be used to "delete" certain
141 /// enum variants from generic types like `Result`.
142 ///
143 /// [`String::from_str`]: str/trait.FromStr.html#tymethod.from_str
144 /// [`Result<String, !>`]: result/enum.Result.html
145 /// [`Result<T, !>`]: result/enum.Result.html
146 /// [`Ok`]: result/enum.Result.html#variant.Ok
147 /// [`String`]: string/struct.String.html
148 /// [`Err`]: result/enum.Result.html#variant.Err
149 /// [`FromStr`]: str/trait.FromStr.html
150 ///
151 /// # `!` and traits
152 ///
153 /// When writing your own traits, `!` should have an `impl` whenever there is an obvious `impl`
154 /// which doesn't `panic!`. As is turns out, most traits can have an `impl` for `!`. Take [`Debug`]
155 /// for example:
156 ///
157 /// ```
158 /// # use std::fmt;
159 /// # trait Debug {
160 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result;
161 /// # }
162 /// impl Debug for ! {
163 ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
164 ///         *self
165 ///     }
166 /// }
167 /// ```
168 ///
169 /// Once again we're using `!`'s ability to coerce into any other type, in this case
170 /// [`fmt::Result`]. Since this method takes a `&!` as an argument we know that it can never be
171 /// called (because there is no value of type `!` for it to be called with). Writing `*self`
172 /// essentially tells the compiler "We know that this code can never be run, so just treat the
173 /// entire function body has having type [`fmt::Result`]". This pattern can be used a lot when
174 /// implementing traits for `!`. Generally, any trait which only has methods which take a `self`
175 /// parameter should have such as impl.
176 ///
177 /// On the other hand, one trait which would not be appropriate to implement is [`Default`]:
178 ///
179 /// ```
180 /// trait Default {
181 ///     fn default() -> Self;
182 /// }
183 /// ```
184 ///
185 /// Since `!` has no values, it has no default value either. It's true that we could write an
186 /// `impl` for this which simply panics, but the same is true for any type (we could `impl
187 /// Default` for (eg.) [`File`] by just making [`default()`] panic.)
188 ///
189 /// [`fmt::Result`]: fmt/type.Result.html
190 /// [`File`]: fs/struct.File.html
191 /// [`Debug`]: fmt/trait.Debug.html
192 /// [`Default`]: default/trait.Default.html
193 /// [`default()`]: default/trait.Default.html#tymethod.default
194 ///
195 mod prim_never { }
196
197 #[doc(primitive = "char")]
198 //
199 /// A character type.
200 ///
201 /// The `char` type represents a single character. More specifically, since
202 /// 'character' isn't a well-defined concept in Unicode, `char` is a '[Unicode
203 /// scalar value]', which is similar to, but not the same as, a '[Unicode code
204 /// point]'.
205 ///
206 /// [Unicode scalar value]: http://www.unicode.org/glossary/#unicode_scalar_value
207 /// [Unicode code point]: http://www.unicode.org/glossary/#code_point
208 ///
209 /// This documentation describes a number of methods and trait implementations on the
210 /// `char` type. For technical reasons, there is additional, separate
211 /// documentation in [the `std::char` module](char/index.html) as well.
212 ///
213 /// # Representation
214 ///
215 /// `char` is always four bytes in size. This is a different representation than
216 /// a given character would have as part of a [`String`]. For example:
217 ///
218 /// ```
219 /// let v = vec!['h', 'e', 'l', 'l', 'o'];
220 ///
221 /// // five elements times four bytes for each element
222 /// assert_eq!(20, v.len() * std::mem::size_of::<char>());
223 ///
224 /// let s = String::from("hello");
225 ///
226 /// // five elements times one byte per element
227 /// assert_eq!(5, s.len() * std::mem::size_of::<u8>());
228 /// ```
229 ///
230 /// [`String`]: string/struct.String.html
231 ///
232 /// As always, remember that a human intuition for 'character' may not map to
233 /// Unicode's definitions. For example, despite looking similar, the 'é'
234 /// character is one Unicode code point while 'é' is two Unicode code points:
235 ///
236 /// ```
237 /// let mut chars = "é".chars();
238 /// // U+00e9: 'latin small letter e with acute'
239 /// assert_eq!(Some('\u{00e9}'), chars.next());
240 /// assert_eq!(None, chars.next());
241 ///
242 /// let mut chars = "é".chars();
243 /// // U+0065: 'latin small letter e'
244 /// assert_eq!(Some('\u{0065}'), chars.next());
245 /// // U+0301: 'combining acute accent'
246 /// assert_eq!(Some('\u{0301}'), chars.next());
247 /// assert_eq!(None, chars.next());
248 /// ```
249 ///
250 /// This means that the contents of the first string above _will_ fit into a
251 /// `char` while the contents of the second string _will not_. Trying to create
252 /// a `char` literal with the contents of the second string gives an error:
253 ///
254 /// ```text
255 /// error: character literal may only contain one codepoint: 'é'
256 /// let c = 'é';
257 ///         ^^^^
258 /// ```
259 ///
260 /// Another implication of the 4-byte fixed size of a `char` is that
261 /// per-`char` processing can end up using a lot more memory:
262 ///
263 /// ```
264 /// let s = String::from("love: ❤️");
265 /// let v: Vec<char> = s.chars().collect();
266 ///
267 /// assert_eq!(12, s.len() * std::mem::size_of::<u8>());
268 /// assert_eq!(32, v.len() * std::mem::size_of::<char>());
269 /// ```
270 #[stable(feature = "rust1", since = "1.0.0")]
271 mod prim_char { }
272
273 #[doc(primitive = "unit")]
274 //
275 /// The `()` type, sometimes called "unit" or "nil".
276 ///
277 /// The `()` type has exactly one value `()`, and is used when there
278 /// is no other meaningful value that could be returned. `()` is most
279 /// commonly seen implicitly: functions without a `-> ...` implicitly
280 /// have return type `()`, that is, these are equivalent:
281 ///
282 /// ```rust
283 /// fn long() -> () {}
284 ///
285 /// fn short() {}
286 /// ```
287 ///
288 /// The semicolon `;` can be used to discard the result of an
289 /// expression at the end of a block, making the expression (and thus
290 /// the block) evaluate to `()`. For example,
291 ///
292 /// ```rust
293 /// fn returns_i64() -> i64 {
294 ///     1i64
295 /// }
296 /// fn returns_unit() {
297 ///     1i64;
298 /// }
299 ///
300 /// let is_i64 = {
301 ///     returns_i64()
302 /// };
303 /// let is_unit = {
304 ///     returns_i64();
305 /// };
306 /// ```
307 ///
308 #[stable(feature = "rust1", since = "1.0.0")]
309 mod prim_unit { }
310
311 #[doc(primitive = "pointer")]
312 //
313 /// Raw, unsafe pointers, `*const T`, and `*mut T`.
314 ///
315 /// Working with raw pointers in Rust is uncommon,
316 /// typically limited to a few patterns.
317 ///
318 /// Use the [`null`] and [`null_mut`] functions to create null pointers, and the
319 /// [`is_null`] method of the `*const T` and `*mut T` types to check for null.
320 /// The `*const T` and `*mut T` types also define the [`offset`] method, for
321 /// pointer math.
322 ///
323 /// # Common ways to create raw pointers
324 ///
325 /// ## 1. Coerce a reference (`&T`) or mutable reference (`&mut T`).
326 ///
327 /// ```
328 /// let my_num: i32 = 10;
329 /// let my_num_ptr: *const i32 = &my_num;
330 /// let mut my_speed: i32 = 88;
331 /// let my_speed_ptr: *mut i32 = &mut my_speed;
332 /// ```
333 ///
334 /// To get a pointer to a boxed value, dereference the box:
335 ///
336 /// ```
337 /// let my_num: Box<i32> = Box::new(10);
338 /// let my_num_ptr: *const i32 = &*my_num;
339 /// let mut my_speed: Box<i32> = Box::new(88);
340 /// let my_speed_ptr: *mut i32 = &mut *my_speed;
341 /// ```
342 ///
343 /// This does not take ownership of the original allocation
344 /// and requires no resource management later,
345 /// but you must not use the pointer after its lifetime.
346 ///
347 /// ## 2. Consume a box (`Box<T>`).
348 ///
349 /// The [`into_raw`] function consumes a box and returns
350 /// the raw pointer. It doesn't destroy `T` or deallocate any memory.
351 ///
352 /// ```
353 /// let my_speed: Box<i32> = Box::new(88);
354 /// let my_speed: *mut i32 = Box::into_raw(my_speed);
355 ///
356 /// // By taking ownership of the original `Box<T>` though
357 /// // we are obligated to put it together later to be destroyed.
358 /// unsafe {
359 ///     drop(Box::from_raw(my_speed));
360 /// }
361 /// ```
362 ///
363 /// Note that here the call to [`drop`] is for clarity - it indicates
364 /// that we are done with the given value and it should be destroyed.
365 ///
366 /// ## 3. Get it from C.
367 ///
368 /// ```
369 /// # #![feature(libc)]
370 /// extern crate libc;
371 ///
372 /// use std::mem;
373 ///
374 /// fn main() {
375 ///     unsafe {
376 ///         let my_num: *mut i32 = libc::malloc(mem::size_of::<i32>()) as *mut i32;
377 ///         if my_num.is_null() {
378 ///             panic!("failed to allocate memory");
379 ///         }
380 ///         libc::free(my_num as *mut libc::c_void);
381 ///     }
382 /// }
383 /// ```
384 ///
385 /// Usually you wouldn't literally use `malloc` and `free` from Rust,
386 /// but C APIs hand out a lot of pointers generally, so are a common source
387 /// of raw pointers in Rust.
388 ///
389 /// *[See also the `std::ptr` module](ptr/index.html).*
390 ///
391 /// [`null`]: ../std/ptr/fn.null.html
392 /// [`null_mut`]: ../std/ptr/fn.null_mut.html
393 /// [`is_null`]: ../std/primitive.pointer.html#method.is_null
394 /// [`offset`]: ../std/primitive.pointer.html#method.offset
395 /// [`into_raw`]: ../std/boxed/struct.Box.html#method.into_raw
396 /// [`drop`]: ../std/mem/fn.drop.html
397 #[stable(feature = "rust1", since = "1.0.0")]
398 mod prim_pointer { }
399
400 #[doc(primitive = "array")]
401 //
402 /// A fixed-size array, denoted `[T; N]`, for the element type, `T`, and the
403 /// non-negative compile-time constant size, `N`.
404 ///
405 /// There are two syntactic forms for creating an array:
406 ///
407 /// * A list with each element, i.e. `[x, y, z]`.
408 /// * A repeat expression `[x; N]`, which produces an array with `N` copies of `x`.
409 ///   The type of `x` must be [`Copy`][copy].
410 ///
411 /// Arrays of sizes from 0 to 32 (inclusive) implement the following traits if
412 /// the element type allows it:
413 ///
414 /// - [`Debug`][debug]
415 /// - [`IntoIterator`][intoiterator] (implemented for `&[T; N]` and `&mut [T; N]`)
416 /// - [`PartialEq`][partialeq], [`PartialOrd`][partialord], [`Eq`][eq], [`Ord`][ord]
417 /// - [`Hash`][hash]
418 /// - [`AsRef`][asref], [`AsMut`][asmut]
419 /// - [`Borrow`][borrow], [`BorrowMut`][borrowmut]
420 /// - [`Default`][default]
421 ///
422 /// This limitation on the size `N` exists because Rust does not yet support
423 /// code that is generic over the size of an array type. `[Foo; 3]` and `[Bar; 3]`
424 /// are instances of same generic type `[T; 3]`, but `[Foo; 3]` and `[Foo; 5]` are
425 /// entirely different types. As a stopgap, trait implementations are
426 /// statically generated up to size 32.
427 ///
428 /// Arrays of *any* size are [`Copy`][copy] if the element type is [`Copy`][copy]
429 /// and [`Clone`][clone] if the element type is [`Clone`][clone]. This works
430 /// because [`Copy`][copy] and [`Clone`][clone] traits are specially known
431 /// to the compiler.
432 ///
433 /// Arrays coerce to [slices (`[T]`)][slice], so a slice method may be called on
434 /// an array. Indeed, this provides most of the API for working with arrays.
435 /// Slices have a dynamic size and do not coerce to arrays.
436 ///
437 /// There is no way to move elements out of an array. See [`mem::replace`][replace]
438 /// for an alternative.
439 ///
440 /// # Examples
441 ///
442 /// ```
443 /// let mut array: [i32; 3] = [0; 3];
444 ///
445 /// array[1] = 1;
446 /// array[2] = 2;
447 ///
448 /// assert_eq!([1, 2], &array[1..]);
449 ///
450 /// // This loop prints: 0 1 2
451 /// for x in &array {
452 ///     print!("{} ", x);
453 /// }
454 /// ```
455 ///
456 /// An array itself is not iterable:
457 ///
458 /// ```compile_fail,E0277
459 /// let array: [i32; 3] = [0; 3];
460 ///
461 /// for x in array { }
462 /// // error: the trait bound `[i32; 3]: std::iter::Iterator` is not satisfied
463 /// ```
464 ///
465 /// The solution is to coerce the array to a slice by calling a slice method:
466 ///
467 /// ```
468 /// # let array: [i32; 3] = [0; 3];
469 /// for x in array.iter() { }
470 /// ```
471 ///
472 /// If the array has 32 or fewer elements (see above), you can also use the
473 /// array reference's [`IntoIterator`] implementation:
474 ///
475 /// ```
476 /// # let array: [i32; 3] = [0; 3];
477 /// for x in &array { }
478 /// ```
479 ///
480 /// [slice]: primitive.slice.html
481 /// [copy]: marker/trait.Copy.html
482 /// [clone]: clone/trait.Clone.html
483 /// [debug]: fmt/trait.Debug.html
484 /// [intoiterator]: iter/trait.IntoIterator.html
485 /// [partialeq]: cmp/trait.PartialEq.html
486 /// [partialord]: cmp/trait.PartialOrd.html
487 /// [eq]: cmp/trait.Eq.html
488 /// [ord]: cmp/trait.Ord.html
489 /// [hash]: hash/trait.Hash.html
490 /// [asref]: convert/trait.AsRef.html
491 /// [asmut]: convert/trait.AsMut.html
492 /// [borrow]: borrow/trait.Borrow.html
493 /// [borrowmut]: borrow/trait.BorrowMut.html
494 /// [default]: default/trait.Default.html
495 /// [replace]: mem/fn.replace.html
496 /// [`IntoIterator`]: iter/trait.IntoIterator.html
497 ///
498 #[stable(feature = "rust1", since = "1.0.0")]
499 mod prim_array { }
500
501 #[doc(primitive = "slice")]
502 //
503 /// A dynamically-sized view into a contiguous sequence, `[T]`.
504 ///
505 /// Slices are a view into a block of memory represented as a pointer and a
506 /// length.
507 ///
508 /// ```
509 /// // slicing a Vec
510 /// let vec = vec![1, 2, 3];
511 /// let int_slice = &vec[..];
512 /// // coercing an array to a slice
513 /// let str_slice: &[&str] = &["one", "two", "three"];
514 /// ```
515 ///
516 /// Slices are either mutable or shared. The shared slice type is `&[T]`,
517 /// while the mutable slice type is `&mut [T]`, where `T` represents the element
518 /// type. For example, you can mutate the block of memory that a mutable slice
519 /// points to:
520 ///
521 /// ```
522 /// let x = &mut [1, 2, 3];
523 /// x[1] = 7;
524 /// assert_eq!(x, &[1, 7, 3]);
525 /// ```
526 ///
527 /// *[See also the `std::slice` module](slice/index.html).*
528 ///
529 #[stable(feature = "rust1", since = "1.0.0")]
530 mod prim_slice { }
531
532 #[doc(primitive = "str")]
533 //
534 /// String slices.
535 ///
536 /// The `str` type, also called a 'string slice', is the most primitive string
537 /// type. It is usually seen in its borrowed form, `&str`. It is also the type
538 /// of string literals, `&'static str`.
539 ///
540 /// Strings slices are always valid UTF-8.
541 ///
542 /// This documentation describes a number of methods and trait implementations
543 /// on the `str` type. For technical reasons, there is additional, separate
544 /// documentation in the [`std::str`](str/index.html) module as well.
545 ///
546 /// # Examples
547 ///
548 /// String literals are string slices:
549 ///
550 /// ```
551 /// let hello = "Hello, world!";
552 ///
553 /// // with an explicit type annotation
554 /// let hello: &'static str = "Hello, world!";
555 /// ```
556 ///
557 /// They are `'static` because they're stored directly in the final binary, and
558 /// so will be valid for the `'static` duration.
559 ///
560 /// # Representation
561 ///
562 /// A `&str` is made up of two components: a pointer to some bytes, and a
563 /// length. You can look at these with the [`as_ptr`] and [`len`] methods:
564 ///
565 /// ```
566 /// use std::slice;
567 /// use std::str;
568 ///
569 /// let story = "Once upon a time...";
570 ///
571 /// let ptr = story.as_ptr();
572 /// let len = story.len();
573 ///
574 /// // story has nineteen bytes
575 /// assert_eq!(19, len);
576 ///
577 /// // We can re-build a str out of ptr and len. This is all unsafe because
578 /// // we are responsible for making sure the two components are valid:
579 /// let s = unsafe {
580 ///     // First, we build a &[u8]...
581 ///     let slice = slice::from_raw_parts(ptr, len);
582 ///
583 ///     // ... and then convert that slice into a string slice
584 ///     str::from_utf8(slice)
585 /// };
586 ///
587 /// assert_eq!(s, Ok(story));
588 /// ```
589 ///
590 /// [`as_ptr`]: #method.as_ptr
591 /// [`len`]: #method.len
592 ///
593 /// Note: This example shows the internals of `&str`. `unsafe` should not be
594 /// used to get a string slice under normal circumstances. Use `as_slice`
595 /// instead.
596 #[stable(feature = "rust1", since = "1.0.0")]
597 mod prim_str { }
598
599 #[doc(primitive = "tuple")]
600 //
601 /// A finite heterogeneous sequence, `(T, U, ..)`.
602 ///
603 /// Let's cover each of those in turn:
604 ///
605 /// Tuples are *finite*. In other words, a tuple has a length. Here's a tuple
606 /// of length `3`:
607 ///
608 /// ```
609 /// ("hello", 5, 'c');
610 /// ```
611 ///
612 /// 'Length' is also sometimes called 'arity' here; each tuple of a different
613 /// length is a different, distinct type.
614 ///
615 /// Tuples are *heterogeneous*. This means that each element of the tuple can
616 /// have a different type. In that tuple above, it has the type:
617 ///
618 /// ```
619 /// # let _:
620 /// (&'static str, i32, char)
621 /// # = ("hello", 5, 'c');
622 /// ```
623 ///
624 /// Tuples are a *sequence*. This means that they can be accessed by position;
625 /// this is called 'tuple indexing', and it looks like this:
626 ///
627 /// ```rust
628 /// let tuple = ("hello", 5, 'c');
629 ///
630 /// assert_eq!(tuple.0, "hello");
631 /// assert_eq!(tuple.1, 5);
632 /// assert_eq!(tuple.2, 'c');
633 /// ```
634 ///
635 /// For more about tuples, see [the book](../book/first-edition/primitive-types.html#tuples).
636 ///
637 /// # Trait implementations
638 ///
639 /// If every type inside a tuple implements one of the following traits, then a
640 /// tuple itself also implements it.
641 ///
642 /// * [`Clone`]
643 /// * [`Copy`]
644 /// * [`PartialEq`]
645 /// * [`Eq`]
646 /// * [`PartialOrd`]
647 /// * [`Ord`]
648 /// * [`Debug`]
649 /// * [`Default`]
650 /// * [`Hash`]
651 ///
652 /// [`Clone`]: clone/trait.Clone.html
653 /// [`Copy`]: marker/trait.Copy.html
654 /// [`PartialEq`]: cmp/trait.PartialEq.html
655 /// [`Eq`]: cmp/trait.Eq.html
656 /// [`PartialOrd`]: cmp/trait.PartialOrd.html
657 /// [`Ord`]: cmp/trait.Ord.html
658 /// [`Debug`]: fmt/trait.Debug.html
659 /// [`Default`]: default/trait.Default.html
660 /// [`Hash`]: hash/trait.Hash.html
661 ///
662 /// Due to a temporary restriction in Rust's type system, these traits are only
663 /// implemented on tuples of arity 12 or less. In the future, this may change.
664 ///
665 /// # Examples
666 ///
667 /// Basic usage:
668 ///
669 /// ```
670 /// let tuple = ("hello", 5, 'c');
671 ///
672 /// assert_eq!(tuple.0, "hello");
673 /// ```
674 ///
675 /// Tuples are often used as a return type when you want to return more than
676 /// one value:
677 ///
678 /// ```
679 /// fn calculate_point() -> (i32, i32) {
680 ///     // Don't do a calculation, that's not the point of the example
681 ///     (4, 5)
682 /// }
683 ///
684 /// let point = calculate_point();
685 ///
686 /// assert_eq!(point.0, 4);
687 /// assert_eq!(point.1, 5);
688 ///
689 /// // Combining this with patterns can be nicer.
690 ///
691 /// let (x, y) = calculate_point();
692 ///
693 /// assert_eq!(x, 4);
694 /// assert_eq!(y, 5);
695 /// ```
696 ///
697 #[stable(feature = "rust1", since = "1.0.0")]
698 mod prim_tuple { }
699
700 #[doc(primitive = "f32")]
701 /// The 32-bit floating point type.
702 ///
703 /// *[See also the `std::f32` module](f32/index.html).*
704 ///
705 #[stable(feature = "rust1", since = "1.0.0")]
706 mod prim_f32 { }
707
708 #[doc(primitive = "f64")]
709 //
710 /// The 64-bit floating point type.
711 ///
712 /// *[See also the `std::f64` module](f64/index.html).*
713 ///
714 #[stable(feature = "rust1", since = "1.0.0")]
715 mod prim_f64 { }
716
717 #[doc(primitive = "i8")]
718 //
719 /// The 8-bit signed integer type.
720 ///
721 /// *[See also the `std::i8` module](i8/index.html).*
722 #[stable(feature = "rust1", since = "1.0.0")]
723 mod prim_i8 { }
724
725 #[doc(primitive = "i16")]
726 //
727 /// The 16-bit signed integer type.
728 ///
729 /// *[See also the `std::i16` module](i16/index.html).*
730 #[stable(feature = "rust1", since = "1.0.0")]
731 mod prim_i16 { }
732
733 #[doc(primitive = "i32")]
734 //
735 /// The 32-bit signed integer type.
736 ///
737 /// *[See also the `std::i32` module](i32/index.html).*
738 #[stable(feature = "rust1", since = "1.0.0")]
739 mod prim_i32 { }
740
741 #[doc(primitive = "i64")]
742 //
743 /// The 64-bit signed integer type.
744 ///
745 /// *[See also the `std::i64` module](i64/index.html).*
746 #[stable(feature = "rust1", since = "1.0.0")]
747 mod prim_i64 { }
748
749 #[doc(primitive = "i128")]
750 //
751 /// The 128-bit signed integer type.
752 ///
753 /// *[See also the `std::i128` module](i128/index.html).*
754 #[unstable(feature = "i128", issue="35118")]
755 mod prim_i128 { }
756
757 #[doc(primitive = "u8")]
758 //
759 /// The 8-bit unsigned integer type.
760 ///
761 /// *[See also the `std::u8` module](u8/index.html).*
762 #[stable(feature = "rust1", since = "1.0.0")]
763 mod prim_u8 { }
764
765 #[doc(primitive = "u16")]
766 //
767 /// The 16-bit unsigned integer type.
768 ///
769 /// *[See also the `std::u16` module](u16/index.html).*
770 #[stable(feature = "rust1", since = "1.0.0")]
771 mod prim_u16 { }
772
773 #[doc(primitive = "u32")]
774 //
775 /// The 32-bit unsigned integer type.
776 ///
777 /// *[See also the `std::u32` module](u32/index.html).*
778 #[stable(feature = "rust1", since = "1.0.0")]
779 mod prim_u32 { }
780
781 #[doc(primitive = "u64")]
782 //
783 /// The 64-bit unsigned integer type.
784 ///
785 /// *[See also the `std::u64` module](u64/index.html).*
786 #[stable(feature = "rust1", since = "1.0.0")]
787 mod prim_u64 { }
788
789 #[doc(primitive = "u128")]
790 //
791 /// The 128-bit unsigned integer type.
792 ///
793 /// *[See also the `std::u128` module](u128/index.html).*
794 #[unstable(feature = "i128", issue="35118")]
795 mod prim_u128 { }
796
797 #[doc(primitive = "isize")]
798 //
799 /// The pointer-sized signed integer type.
800 ///
801 /// The size of this primitive is how many bytes it takes to reference any
802 /// location in memory. For example, on a 32 bit target, this is 4 bytes
803 /// and on a 64 bit target, this is 8 bytes.
804 ///
805 /// *[See also the `std::isize` module](isize/index.html).*
806 #[stable(feature = "rust1", since = "1.0.0")]
807 mod prim_isize { }
808
809 #[doc(primitive = "usize")]
810 //
811 /// The pointer-sized unsigned integer type.
812 ///
813 /// The size of this primitive is how many bytes it takes to reference any
814 /// location in memory. For example, on a 32 bit target, this is 4 bytes
815 /// and on a 64 bit target, this is 8 bytes.
816 ///
817 /// *[See also the `std::usize` module](usize/index.html).*
818 #[stable(feature = "rust1", since = "1.0.0")]
819 mod prim_usize { }
820
821 #[doc(primitive = "reference")]
822 //
823 /// References, both shared and mutable.
824 ///
825 /// A reference represents a borrow of some owned value. You can get one by using the `&` or `&mut`
826 /// operators on a value, or by using a `ref` or `ref mut` pattern.
827 ///
828 /// For those familiar with pointers, a reference is just a pointer that is assumed to not be null.
829 /// In fact, `Option<&T>` has the same memory representation as a nullable pointer, and can be
830 /// passed across FFI boundaries as such.
831 ///
832 /// In most cases, references can be used much like the original value. Field access, method
833 /// calling, and indexing work the same (save for mutability rules, of course). In addition, the
834 /// comparison operators transparently defer to the referent's implementation, allowing references
835 /// to be compared the same as owned values.
836 ///
837 /// References have a lifetime attached to them, which represents the scope for which the borrow is
838 /// valid. A lifetime is said to "outlive" another one if its representative scope is as long or
839 /// longer than the other. The `'static` lifetime is the longest lifetime, which represents the
840 /// total life of the program. For example, string literals have a `'static` lifetime because the
841 /// text data is embedded into the binary of the program, rather than in an allocation that needs
842 /// to be dynamically managed.
843 ///
844 /// `&mut T` references can be freely coerced into `&T` references with the same referent type, and
845 /// references with longer lifetimes can be freely coerced into references with shorter ones.
846 ///
847 /// For more information on how to use references, see [the book's section on "References and
848 /// Borrowing"][book-refs].
849 ///
850 /// [book-refs]: ../book/second-edition/ch04-02-references-and-borrowing.html
851 ///
852 /// The following traits are implemented for all `&T`, regardless of the type of its referent:
853 ///
854 /// * [`Copy`]
855 /// * [`Clone`] \(Note that this will not defer to `T`'s `Clone` implementation if it exists!)
856 /// * [`Deref`]
857 /// * [`Borrow`]
858 /// * [`Pointer`]
859 ///
860 /// [`Copy`]: marker/trait.Copy.html
861 /// [`Clone`]: clone/trait.Clone.html
862 /// [`Deref`]: ops/trait.Deref.html
863 /// [`Borrow`]: borrow/trait.Borrow.html
864 /// [`Pointer`]: fmt/trait.Pointer.html
865 ///
866 /// `&mut T` references get all of the above except `Copy` and `Clone` (to prevent creating
867 /// multiple simultaneous mutable borrows), plus the following, regardless of the type of its
868 /// referent:
869 ///
870 /// * [`DerefMut`]
871 /// * [`BorrowMut`]
872 ///
873 /// [`DerefMut`]: ops/trait.DerefMut.html
874 /// [`BorrowMut`]: borrow/trait.BorrowMut.html
875 ///
876 /// The following traits are implemented on `&T` references if the underlying `T` also implements
877 /// that trait:
878 ///
879 /// * All the traits in [`std::fmt`] except [`Pointer`] and [`fmt::Write`]
880 /// * [`PartialOrd`]
881 /// * [`Ord`]
882 /// * [`PartialEq`]
883 /// * [`Eq`]
884 /// * [`AsRef`]
885 /// * [`Fn`] \(in addition, `&T` references get [`FnMut`] and [`FnOnce`] if `T: Fn`)
886 /// * [`Hash`]
887 /// * [`ToSocketAddrs`]
888 ///
889 /// [`std::fmt`]: fmt/index.html
890 /// [`fmt::Write`]: fmt/trait.Write.html
891 /// [`PartialOrd`]: cmp/trait.PartialOrd.html
892 /// [`Ord`]: cmp/trait.Ord.html
893 /// [`PartialEq`]: cmp/trait.PartialEq.html
894 /// [`Eq`]: cmp/trait.Eq.html
895 /// [`AsRef`]: convert/trait.AsRef.html
896 /// [`Fn`]: ops/trait.Fn.html
897 /// [`FnMut`]: ops/trait.FnMut.html
898 /// [`FnOnce`]: ops/trait.FnOnce.html
899 /// [`Hash`]: hash/trait.Hash.html
900 /// [`ToSocketAddrs`]: net/trait.ToSocketAddrs.html
901 ///
902 /// `&mut T` references get all of the above except `ToSocketAddrs`, plus the following, if `T`
903 /// implements that trait:
904 ///
905 /// * [`AsMut`]
906 /// * [`FnMut`] \(in addition, `&mut T` references get [`FnOnce`] if `T: FnMut`)
907 /// * [`fmt::Write`]
908 /// * [`Iterator`]
909 /// * [`DoubleEndedIterator`]
910 /// * [`ExactSizeIterator`]
911 /// * [`FusedIterator`]
912 /// * [`TrustedLen`]
913 /// * [`Send`] \(note that `&T` references only get `Send` if `T: Sync`)
914 /// * [`io::Write`]
915 /// * [`Read`]
916 /// * [`Seek`]
917 /// * [`BufRead`]
918 ///
919 /// [`AsMut`]: convert/trait.AsMut.html
920 /// [`Iterator`]: iter/trait.Iterator.html
921 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
922 /// [`ExactSizeIterator`]: iter/trait.ExactSizeIterator.html
923 /// [`FusedIterator`]: iter/trait.FusedIterator.html
924 /// [`TrustedLen`]: iter/trait.TrustedLen.html
925 /// [`Send`]: marker/trait.Send.html
926 /// [`io::Write`]: io/trait.Write.html
927 /// [`Read`]: io/trait.Read.html
928 /// [`Seek`]: io/trait.Seek.html
929 /// [`BufRead`]: io/trait.BufRead.html
930 ///
931 /// Note that due to method call deref coercion, simply calling a trait method will act like they
932 /// work on references as well as they do on owned values! The implementations described here are
933 /// meant for generic contexts, where the final type `T` is a type parameter or otherwise not
934 /// locally known.
935 #[stable(feature = "rust1", since = "1.0.0")]
936 mod prim_ref { }
937
938 #[doc(primitive = "fn")]
939 //
940 /// Function pointers, like `fn(usize) -> bool`.
941 ///
942 /// *See also the traits [`Fn`], [`FnMut`], and [`FnOnce`].*
943 ///
944 /// [`Fn`]: ops/trait.Fn.html
945 /// [`FnMut`]: ops/trait.FnMut.html
946 /// [`FnOnce`]: ops/trait.FnOnce.html
947 ///
948 /// Plain function pointers are obtained by casting either plain functions, or closures that don't
949 /// capture an environment:
950 ///
951 /// ```
952 /// fn add_one(x: usize) -> usize {
953 ///     x + 1
954 /// }
955 ///
956 /// let ptr: fn(usize) -> usize = add_one;
957 /// assert_eq!(ptr(5), 6);
958 ///
959 /// let clos: fn(usize) -> usize = |x| x + 5;
960 /// assert_eq!(clos(5), 10);
961 /// ```
962 ///
963 /// In addition to varying based on their signature, function pointers come in two flavors: safe
964 /// and unsafe. Plain `fn()` function pointers can only point to safe functions,
965 /// while `unsafe fn()` function pointers can point to safe or unsafe functions.
966 ///
967 /// ```
968 /// fn add_one(x: usize) -> usize {
969 ///     x + 1
970 /// }
971 ///
972 /// unsafe fn add_one_unsafely(x: usize) -> usize {
973 ///     x + 1
974 /// }
975 ///
976 /// let safe_ptr: fn(usize) -> usize = add_one;
977 ///
978 /// //ERROR: mismatched types: expected normal fn, found unsafe fn
979 /// //let bad_ptr: fn(usize) -> usize = add_one_unsafely;
980 ///
981 /// let unsafe_ptr: unsafe fn(usize) -> usize = add_one_unsafely;
982 /// let really_safe_ptr: unsafe fn(usize) -> usize = add_one;
983 /// ```
984 ///
985 /// On top of that, function pointers can vary based on what ABI they use. This is achieved by
986 /// adding the `extern` keyword to the type name, followed by the ABI in question. For example,
987 /// `fn()` is different from `extern "C" fn()`, which itself is different from `extern "stdcall"
988 /// fn()`, and so on for the various ABIs that Rust supports.  Non-`extern` functions have an ABI
989 /// of `"Rust"`, and `extern` functions without an explicit ABI have an ABI of `"C"`. For more
990 /// information, see [the nomicon's section on foreign calling conventions][nomicon-abi].
991 ///
992 /// [nomicon-abi]: ../nomicon/ffi.html#foreign-calling-conventions
993 ///
994 /// Extern function declarations with the "C" or "cdecl" ABIs can also be *variadic*, allowing them
995 /// to be called with a variable number of arguments. Normal rust functions, even those with an
996 /// `extern "ABI"`, cannot be variadic. For more information, see [the nomicon's section on
997 /// variadic functions][nomicon-variadic].
998 ///
999 /// [nomicon-variadic]: ../nomicon/ffi.html#variadic-functions
1000 ///
1001 /// These markers can be combined, so `unsafe extern "stdcall" fn()` is a valid type.
1002 ///
1003 /// Like references in rust, function pointers are assumed to not be null, so if you want to pass a
1004 /// function pointer over FFI and be able to accommodate null pointers, make your type
1005 /// `Option<fn()>` with your required signature.
1006 ///
1007 /// Function pointers implement the following traits:
1008 ///
1009 /// * [`Clone`]
1010 /// * [`PartialEq`]
1011 /// * [`Eq`]
1012 /// * [`PartialOrd`]
1013 /// * [`Ord`]
1014 /// * [`Hash`]
1015 /// * [`Pointer`]
1016 /// * [`Debug`]
1017 ///
1018 /// [`Clone`]: clone/trait.Clone.html
1019 /// [`PartialEq`]: cmp/trait.PartialEq.html
1020 /// [`Eq`]: cmp/trait.Eq.html
1021 /// [`PartialOrd`]: cmp/trait.PartialOrd.html
1022 /// [`Ord`]: cmp/trait.Ord.html
1023 /// [`Hash`]: hash/trait.Hash.html
1024 /// [`Pointer`]: fmt/trait.Pointer.html
1025 /// [`Debug`]: fmt/trait.Debug.html
1026 ///
1027 /// Due to a temporary restriction in Rust's type system, these traits are only implemented on
1028 /// functions that take 12 arguments or less, with the `"Rust"` and `"C"` ABIs. In the future, this
1029 /// may change.
1030 ///
1031 /// In addition, function pointers of *any* signature, ABI, or safety are [`Copy`], and all *safe*
1032 /// function pointers implement [`Fn`], [`FnMut`], and [`FnOnce`]. This works because these traits
1033 /// are specially known to the compiler.
1034 ///
1035 /// [`Copy`]: marker/trait.Copy.html
1036 #[stable(feature = "rust1", since = "1.0.0")]
1037 mod prim_fn { }