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