xref: /drstd/src/std/primitive_docs.rs (revision 9670759b785600bf6315e4173e46a602f16add7a)
1 // `library/{std,core}/src/primitive_docs.rs` should have the same contents.
2 // These are different files so that relative links work properly without
3 // having to have `CARGO_PKG_NAME` set, but conceptually they should always be the same.
4 #[rustc_doc_primitive = "bool"]
5 #[doc(alias = "true")]
6 #[doc(alias = "false")]
7 /// The boolean type.
8 ///
9 /// The `bool` represents a value, which could only be either [`true`] or [`false`]. If you cast
10 /// a `bool` into an integer, [`true`] will be 1 and [`false`] will be 0.
11 ///
12 /// # Basic usage
13 ///
14 /// `bool` implements various traits, such as [`BitAnd`], [`BitOr`], [`Not`], etc.,
15 /// which allow us to perform boolean operations using `&`, `|` and `!`.
16 ///
17 /// [`if`] requires a `bool` value as its conditional. [`assert!`], which is an
18 /// important macro in testing, checks whether an expression is [`true`] and panics
19 /// if it isn't.
20 ///
21 /// ```
22 /// let bool_val = true & false | false;
23 /// assert!(!bool_val);
24 /// ```
25 ///
26 /// [`true`]: ../std/keyword.true.html
27 /// [`false`]: ../std/keyword.false.html
28 /// [`BitAnd`]: ops::BitAnd
29 /// [`BitOr`]: ops::BitOr
30 /// [`Not`]: ops::Not
31 /// [`if`]: ../std/keyword.if.html
32 ///
33 /// # Examples
34 ///
35 /// A trivial example of the usage of `bool`:
36 ///
37 /// ```
38 /// let praise_the_borrow_checker = true;
39 ///
40 /// // using the `if` conditional
41 /// if praise_the_borrow_checker {
42 ///     println!("oh, yeah!");
43 /// } else {
44 ///     println!("what?!!");
45 /// }
46 ///
47 /// // ... or, a match pattern
48 /// match praise_the_borrow_checker {
49 ///     true => println!("keep praising!"),
50 ///     false => println!("you should praise!"),
51 /// }
52 /// ```
53 ///
54 /// Also, since `bool` implements the [`Copy`] trait, we don't
55 /// have to worry about the move semantics (just like the integer and float primitives).
56 ///
57 /// Now an example of `bool` cast to integer type:
58 ///
59 /// ```
60 /// assert_eq!(true as i32, 1);
61 /// assert_eq!(false as i32, 0);
62 /// ```
63 mod prim_bool {}
64 
65 #[rustc_doc_primitive = "never"]
66 #[doc(alias = "!")]
67 //
68 /// The `!` type, also called "never".
69 ///
70 /// `!` represents the type of computations which never resolve to any value at all. For example,
71 /// the [`exit`] function `fn exit(code: i32) -> !` exits the process without ever returning, and
72 /// so returns `!`.
73 ///
74 /// `break`, `continue` and `return` expressions also have type `!`. For example we are allowed to
75 /// write:
76 ///
77 /// ```
78 /// #![feature(never_type)]
79 /// # fn foo() -> u32 {
80 /// let x: ! = {
81 ///     return 123
82 /// };
83 /// # }
84 /// ```
85 ///
86 /// Although the `let` is pointless here, it illustrates the meaning of `!`. Since `x` is never
87 /// assigned a value (because `return` returns from the entire function), `x` can be given type
88 /// `!`. We could also replace `return 123` with a `panic!` or a never-ending `loop` and this code
89 /// would still be valid.
90 ///
91 /// A more realistic usage of `!` is in this code:
92 ///
93 /// ```
94 /// # fn get_a_number() -> Option<u32> { None }
95 /// # loop {
96 /// let num: u32 = match get_a_number() {
97 ///     Some(num) => num,
98 ///     None => break,
99 /// };
100 /// # }
101 /// ```
102 ///
103 /// Both match arms must produce values of type [`u32`], but since `break` never produces a value
104 /// at all we know it can never produce a value which isn't a [`u32`]. This illustrates another
105 /// behaviour of the `!` type - expressions with type `!` will coerce into any other type.
106 ///
107 /// [`u32`]: prim@u32
108 //#[doc = concat!("[`exit`]: ", include_str!("../primitive_docs/process_exit.md"))]
109 ///
110 /// # `!` and generics
111 ///
112 /// ## Infallible errors
113 ///
114 /// The main place you'll see `!` used explicitly is in generic code. Consider the [`FromStr`]
115 /// trait:
116 ///
117 /// ```
118 /// trait FromStr: Sized {
119 ///     type Err;
120 ///     fn from_str(s: &str) -> Result<Self, Self::Err>;
121 /// }
122 /// ```
123 ///
124 /// When implementing this trait for [`String`] we need to pick a type for [`Err`]. And since
125 /// converting a string into a string will never result in an error, the appropriate type is `!`.
126 /// (Currently the type actually used is an enum with no variants, though this is only because `!`
127 /// was added to Rust at a later date and it may change in the future.) With an [`Err`] type of
128 /// `!`, if we have to call [`String::from_str`] for some reason the result will be a
129 /// [`Result<String, !>`] which we can unpack like this:
130 ///
131 /// ```
132 /// #![feature(exhaustive_patterns)]
133 /// use std::str::FromStr;
134 /// let Ok(s) = String::from_str("hello");
135 /// ```
136 ///
137 /// Since the [`Err`] variant contains a `!`, it can never occur. If the `exhaustive_patterns`
138 /// feature is present this means we can exhaustively match on [`Result<T, !>`] by just taking the
139 /// [`Ok`] variant. This illustrates another behaviour of `!` - it can be used to "delete" certain
140 /// enum variants from generic types like `Result`.
141 ///
142 /// ## Infinite loops
143 ///
144 /// While [`Result<T, !>`] is very useful for removing errors, `!` can also be used to remove
145 /// successes as well. If we think of [`Result<T, !>`] as "if this function returns, it has not
146 /// errored," we get a very intuitive idea of [`Result<!, E>`] as well: if the function returns, it
147 /// *has* errored.
148 ///
149 /// For example, consider the case of a simple web server, which can be simplified to:
150 ///
151 /// ```ignore (hypothetical-example)
152 /// loop {
153 ///     let (client, request) = get_request().expect("disconnected");
154 ///     let response = request.process();
155 ///     response.send(client);
156 /// }
157 /// ```
158 ///
159 /// Currently, this isn't ideal, because we simply panic whenever we fail to get a new connection.
160 /// Instead, we'd like to keep track of this error, like this:
161 ///
162 /// ```ignore (hypothetical-example)
163 /// loop {
164 ///     match get_request() {
165 ///         Err(err) => break err,
166 ///         Ok((client, request)) => {
167 ///             let response = request.process();
168 ///             response.send(client);
169 ///         },
170 ///     }
171 /// }
172 /// ```
173 ///
174 /// Now, when the server disconnects, we exit the loop with an error instead of panicking. While it
175 /// might be intuitive to simply return the error, we might want to wrap it in a [`Result<!, E>`]
176 /// instead:
177 ///
178 /// ```ignore (hypothetical-example)
179 /// fn server_loop() -> Result<!, ConnectionError> {
180 ///     loop {
181 ///         let (client, request) = get_request()?;
182 ///         let response = request.process();
183 ///         response.send(client);
184 ///     }
185 /// }
186 /// ```
187 ///
188 /// Now, we can use `?` instead of `match`, and the return type makes a lot more sense: if the loop
189 /// ever stops, it means that an error occurred. We don't even have to wrap the loop in an `Ok`
190 /// because `!` coerces to `Result<!, ConnectionError>` automatically.
191 ///
192 /// [`String::from_str`]: str::FromStr::from_str
193 //#[doc = concat!("[`String`]: ", include_str!("../primitive_docs/string_string.md"))]
194 /// [`FromStr`]: str::FromStr
195 ///
196 /// # `!` and traits
197 ///
198 /// When writing your own traits, `!` should have an `impl` whenever there is an obvious `impl`
199 /// which doesn't `panic!`. The reason is that functions returning an `impl Trait` where `!`
200 /// does not have an `impl` of `Trait` cannot diverge as their only possible code path. In other
201 /// words, they can't return `!` from every code path. As an example, this code doesn't compile:
202 ///
203 /// ```compile_fail
204 /// use std::ops::Add;
205 ///
206 /// fn foo() -> impl Add<u32> {
207 ///     unimplemented!()
208 /// }
209 /// ```
210 ///
211 /// But this code does:
212 ///
213 /// ```
214 /// use std::ops::Add;
215 ///
216 /// fn foo() -> impl Add<u32> {
217 ///     if true {
218 ///         unimplemented!()
219 ///     } else {
220 ///         0
221 ///     }
222 /// }
223 /// ```
224 ///
225 /// The reason is that, in the first example, there are many possible types that `!` could coerce
226 /// to, because many types implement `Add<u32>`. However, in the second example,
227 /// the `else` branch returns a `0`, which the compiler infers from the return type to be of type
228 /// `u32`. Since `u32` is a concrete type, `!` can and will be coerced to it. See issue [#36375]
229 /// for more information on this quirk of `!`.
230 ///
231 /// [#36375]: https://github.com/rust-lang/rust/issues/36375
232 ///
233 /// As it turns out, though, most traits can have an `impl` for `!`. Take [`Debug`]
234 /// for example:
235 ///
236 /// ```
237 /// #![feature(never_type)]
238 /// # use std::fmt;
239 /// # trait Debug {
240 /// #     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result;
241 /// # }
242 /// impl Debug for ! {
243 ///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
244 ///         *self
245 ///     }
246 /// }
247 /// ```
248 ///
249 /// Once again we're using `!`'s ability to coerce into any other type, in this case
250 /// [`fmt::Result`]. Since this method takes a `&!` as an argument we know that it can never be
251 /// called (because there is no value of type `!` for it to be called with). Writing `*self`
252 /// essentially tells the compiler "We know that this code can never be run, so just treat the
253 /// entire function body as having type [`fmt::Result`]". This pattern can be used a lot when
254 /// implementing traits for `!`. Generally, any trait which only has methods which take a `self`
255 /// parameter should have such an impl.
256 ///
257 /// On the other hand, one trait which would not be appropriate to implement is [`Default`]:
258 ///
259 /// ```
260 /// trait Default {
261 ///     fn default() -> Self;
262 /// }
263 /// ```
264 ///
265 /// Since `!` has no values, it has no default value either. It's true that we could write an
266 /// `impl` for this which simply panics, but the same is true for any type (we could `impl
267 /// Default` for (eg.) [`File`] by just making [`default()`] panic.)
268 ///
269 //#[doc = concat!("[`File`]: ", include_str!("../primitive_docs/fs_file.md"))]
270 /// [`Debug`]: fmt::Debug
271 /// [`default()`]: Default::default
272 ///
273 mod prim_never {}
274 
275 #[rustc_doc_primitive = "char"]
276 #[allow(rustdoc::invalid_rust_codeblocks)]
277 /// A character type.
278 ///
279 /// The `char` type represents a single character. More specifically, since
280 /// 'character' isn't a well-defined concept in Unicode, `char` is a '[Unicode
281 /// scalar value]'.
282 ///
283 /// This documentation describes a number of methods and trait implementations on the
284 /// `char` type. For technical reasons, there is additional, separate
285 /// documentation in [the `std::char` module](char/index.html) as well.
286 ///
287 /// # Validity
288 ///
289 /// A `char` is a '[Unicode scalar value]', which is any '[Unicode code point]'
290 /// other than a [surrogate code point]. This has a fixed numerical definition:
291 /// code points are in the range 0 to 0x10FFFF, inclusive.
292 /// Surrogate code points, used by UTF-16, are in the range 0xD800 to 0xDFFF.
293 ///
294 /// No `char` may be constructed, whether as a literal or at runtime, that is not a
295 /// Unicode scalar value:
296 ///
297 /// ```compile_fail
298 /// // Each of these is a compiler error
299 /// ['\u{D800}', '\u{DFFF}', '\u{110000}'];
300 /// ```
301 ///
302 /// ```should_panic
303 /// // Panics; from_u32 returns None.
304 /// char::from_u32(0xDE01).unwrap();
305 /// ```
306 ///
307 /// ```no_run
308 /// // Undefined behaviour
309 /// let _ = unsafe { char::from_u32_unchecked(0x110000) };
310 /// ```
311 ///
312 /// USVs are also the exact set of values that may be encoded in UTF-8. Because
313 /// `char` values are USVs and `str` values are valid UTF-8, it is safe to store
314 /// any `char` in a `str` or read any character from a `str` as a `char`.
315 ///
316 /// The gap in valid `char` values is understood by the compiler, so in the
317 /// below example the two ranges are understood to cover the whole range of
318 /// possible `char` values and there is no error for a [non-exhaustive match].
319 ///
320 /// ```
321 /// let c: char = 'a';
322 /// match c {
323 ///     '\0' ..= '\u{D7FF}' => false,
324 ///     '\u{E000}' ..= '\u{10FFFF}' => true,
325 /// };
326 /// ```
327 ///
328 /// All USVs are valid `char` values, but not all of them represent a real
329 /// character. Many USVs are not currently assigned to a character, but may be
330 /// in the future ("reserved"); some will never be a character
331 /// ("noncharacters"); and some may be given different meanings by different
332 /// users ("private use").
333 ///
334 /// [Unicode code point]: https://www.unicode.org/glossary/#code_point
335 /// [Unicode scalar value]: https://www.unicode.org/glossary/#unicode_scalar_value
336 /// [non-exhaustive match]: ../book/ch06-02-match.html#matches-are-exhaustive
337 /// [surrogate code point]: https://www.unicode.org/glossary/#surrogate_code_point
338 ///
339 /// # Representation
340 ///
341 /// `char` is always four bytes in size. This is a different representation than
342 /// a given character would have as part of a [`String`]. For example:
343 ///
344 /// ```
345 /// let v = vec!['h', 'e', 'l', 'l', 'o'];
346 ///
347 /// // five elements times four bytes for each element
348 /// assert_eq!(20, v.len() * std::mem::size_of::<char>());
349 ///
350 /// let s = String::from("hello");
351 ///
352 /// // five elements times one byte per element
353 /// assert_eq!(5, s.len() * std::mem::size_of::<u8>());
354 /// ```
355 ///
356 //#[doc = concat!("[`String`]: ", include_str!("../primitive_docs/string_string.md"))]
357 ///
358 /// As always, remember that a human intuition for 'character' might not map to
359 /// Unicode's definitions. For example, despite looking similar, the 'é'
360 /// character is one Unicode code point while 'é' is two Unicode code points:
361 ///
362 /// ```
363 /// let mut chars = "é".chars();
364 /// // U+00e9: 'latin small letter e with acute'
365 /// assert_eq!(Some('\u{00e9}'), chars.next());
366 /// assert_eq!(None, chars.next());
367 ///
368 /// let mut chars = "é".chars();
369 /// // U+0065: 'latin small letter e'
370 /// assert_eq!(Some('\u{0065}'), chars.next());
371 /// // U+0301: 'combining acute accent'
372 /// assert_eq!(Some('\u{0301}'), chars.next());
373 /// assert_eq!(None, chars.next());
374 /// ```
375 ///
376 /// This means that the contents of the first string above _will_ fit into a
377 /// `char` while the contents of the second string _will not_. Trying to create
378 /// a `char` literal with the contents of the second string gives an error:
379 ///
380 /// ```text
381 /// error: character literal may only contain one codepoint: 'é'
382 /// let c = 'é';
383 ///         ^^^
384 /// ```
385 ///
386 /// Another implication of the 4-byte fixed size of a `char` is that
387 /// per-`char` processing can end up using a lot more memory:
388 ///
389 /// ```
390 /// let s = String::from("love: ❤️");
391 /// let v: Vec<char> = s.chars().collect();
392 ///
393 /// assert_eq!(12, std::mem::size_of_val(&s[..]));
394 /// assert_eq!(32, std::mem::size_of_val(&v[..]));
395 /// ```
396 mod prim_char {}
397 
398 #[rustc_doc_primitive = "unit"]
399 #[doc(alias = "(")]
400 #[doc(alias = ")")]
401 #[doc(alias = "()")]
402 //
403 /// The `()` type, also called "unit".
404 ///
405 /// The `()` type has exactly one value `()`, and is used when there
406 /// is no other meaningful value that could be returned. `()` is most
407 /// commonly seen implicitly: functions without a `-> ...` implicitly
408 /// have return type `()`, that is, these are equivalent:
409 ///
410 /// ```rust
411 /// fn long() -> () {}
412 ///
413 /// fn short() {}
414 /// ```
415 ///
416 /// The semicolon `;` can be used to discard the result of an
417 /// expression at the end of a block, making the expression (and thus
418 /// the block) evaluate to `()`. For example,
419 ///
420 /// ```rust
421 /// fn returns_i64() -> i64 {
422 ///     1i64
423 /// }
424 /// fn returns_unit() {
425 ///     1i64;
426 /// }
427 ///
428 /// let is_i64 = {
429 ///     returns_i64()
430 /// };
431 /// let is_unit = {
432 ///     returns_i64();
433 /// };
434 /// ```
435 ///
436 mod prim_unit {}
437 
438 // Required to make auto trait impls render.
439 // See src/librustdoc/passes/collect_trait_impls.rs:collect_trait_impls
440 #[doc(hidden)]
441 impl () {}
442 
443 // Fake impl that's only really used for docs.
444 #[cfg(doc)]
445 impl Clone for () {
clone(&self) -> Self446     fn clone(&self) -> Self {
447         loop {}
448     }
449 }
450 
451 // Fake impl that's only really used for docs.
452 #[cfg(doc)]
453 impl Copy for () {
454     // empty
455 }
456 
457 #[rustc_doc_primitive = "pointer"]
458 #[doc(alias = "ptr")]
459 #[doc(alias = "*")]
460 #[doc(alias = "*const")]
461 #[doc(alias = "*mut")]
462 //
463 /// Raw, unsafe pointers, `*const T`, and `*mut T`.
464 ///
465 /// *[See also the `std::ptr` module](ptr).*
466 ///
467 /// Working with raw pointers in Rust is uncommon, typically limited to a few patterns.
468 /// Raw pointers can be unaligned or [`null`]. However, when a raw pointer is
469 /// dereferenced (using the `*` operator), it must be non-null and aligned.
470 ///
471 /// Storing through a raw pointer using `*ptr = data` calls `drop` on the old value, so
472 /// [`write`] must be used if the type has drop glue and memory is not already
473 /// initialized - otherwise `drop` would be called on the uninitialized memory.
474 ///
475 /// Use the [`null`] and [`null_mut`] functions to create null pointers, and the
476 /// [`is_null`] method of the `*const T` and `*mut T` types to check for null.
477 /// The `*const T` and `*mut T` types also define the [`offset`] method, for
478 /// pointer math.
479 ///
480 /// # Common ways to create raw pointers
481 ///
482 /// ## 1. Coerce a reference (`&T`) or mutable reference (`&mut T`).
483 ///
484 /// ```
485 /// let my_num: i32 = 10;
486 /// let my_num_ptr: *const i32 = &my_num;
487 /// let mut my_speed: i32 = 88;
488 /// let my_speed_ptr: *mut i32 = &mut my_speed;
489 /// ```
490 ///
491 /// To get a pointer to a boxed value, dereference the box:
492 ///
493 /// ```
494 /// let my_num: Box<i32> = Box::new(10);
495 /// let my_num_ptr: *const i32 = &*my_num;
496 /// let mut my_speed: Box<i32> = Box::new(88);
497 /// let my_speed_ptr: *mut i32 = &mut *my_speed;
498 /// ```
499 ///
500 /// This does not take ownership of the original allocation
501 /// and requires no resource management later,
502 /// but you must not use the pointer after its lifetime.
503 ///
504 /// ## 2. Consume a box (`Box<T>`).
505 ///
506 /// The [`into_raw`] function consumes a box and returns
507 /// the raw pointer. It doesn't destroy `T` or deallocate any memory.
508 ///
509 /// ```
510 /// let my_speed: Box<i32> = Box::new(88);
511 /// let my_speed: *mut i32 = Box::into_raw(my_speed);
512 ///
513 /// // By taking ownership of the original `Box<T>` though
514 /// // we are obligated to put it together later to be destroyed.
515 /// unsafe {
516 ///     drop(Box::from_raw(my_speed));
517 /// }
518 /// ```
519 ///
520 /// Note that here the call to [`drop`] is for clarity - it indicates
521 /// that we are done with the given value and it should be destroyed.
522 ///
523 /// ## 3. Create it using `ptr::addr_of!`
524 ///
525 /// Instead of coercing a reference to a raw pointer, you can use the macros
526 /// [`ptr::addr_of!`] (for `*const T`) and [`ptr::addr_of_mut!`] (for `*mut T`).
527 /// These macros allow you to create raw pointers to fields to which you cannot
528 /// create a reference (without causing undefined behaviour), such as an
529 /// unaligned field. This might be necessary if packed structs or uninitialized
530 /// memory is involved.
531 ///
532 /// ```
533 /// #[derive(Debug, Default, Copy, Clone)]
534 /// #[repr(C, packed)]
535 /// struct S {
536 ///     aligned: u8,
537 ///     unaligned: u32,
538 /// }
539 /// let s = S::default();
540 /// let p = std::ptr::addr_of!(s.unaligned); // not allowed with coercion
541 /// ```
542 ///
543 /// ## 4. Get it from C.
544 ///
545 /// ```
546 /// # #![feature(rustc_private)]
547 /// #[allow(unused_extern_crates)]
548 /// extern crate libc;
549 ///
550 /// use std::mem;
551 ///
552 /// unsafe {
553 ///     let my_num: *mut i32 = dlibc::malloc(mem::size_of::<i32>()) as *mut i32;
554 ///     if my_num.is_null() {
555 ///         panic!("failed to allocate memory");
556 ///     }
557 ///     dlibc::free(my_num as *mut dlibc::c_void);
558 /// }
559 /// ```
560 ///
561 /// Usually you wouldn't literally use `malloc` and `free` from Rust,
562 /// but C APIs hand out a lot of pointers generally, so are a common source
563 /// of raw pointers in Rust.
564 ///
565 /// [`null`]: ptr::null
566 /// [`null_mut`]: ptr::null_mut
567 /// [`is_null`]: pointer::is_null
568 /// [`offset`]: pointer::offset
569 //#[doc = concat!("[`into_raw`]: ", include_str!("../primitive_docs/box_into_raw.md"))]
570 /// [`write`]: ptr::write
571 mod prim_pointer {}
572 
573 #[rustc_doc_primitive = "array"]
574 #[doc(alias = "[]")]
575 #[doc(alias = "[T;N]")] // unfortunately, rustdoc doesn't have fuzzy search for aliases
576 #[doc(alias = "[T; N]")]
577 /// A fixed-size array, denoted `[T; N]`, for the element type, `T`, and the
578 /// non-negative compile-time constant size, `N`.
579 ///
580 /// There are two syntactic forms for creating an array:
581 ///
582 /// * A list with each element, i.e., `[x, y, z]`.
583 /// * A repeat expression `[expr; N]` where `N` is how many times to repeat `expr` in the array. `expr` must either be:
584 ///
585 ///   * A value of a type implementing the [`Copy`] trait
586 ///   * A `const` value
587 ///
588 /// Note that `[expr; 0]` is allowed, and produces an empty array.
589 /// This will still evaluate `expr`, however, and immediately drop the resulting value, so
590 /// be mindful of side effects.
591 ///
592 /// Arrays of *any* size implement the following traits if the element type allows it:
593 ///
594 /// - [`Copy`]
595 /// - [`Clone`]
596 /// - [`Debug`]
597 /// - [`IntoIterator`] (implemented for `[T; N]`, `&[T; N]` and `&mut [T; N]`)
598 /// - [`PartialEq`], [`PartialOrd`], [`Eq`], [`Ord`]
599 /// - [`Hash`]
600 /// - [`AsRef`], [`AsMut`]
601 /// - [`Borrow`], [`BorrowMut`]
602 ///
603 /// Arrays of sizes from 0 to 32 (inclusive) implement the [`Default`] trait
604 /// if the element type allows it. As a stopgap, trait implementations are
605 /// statically generated up to size 32.
606 ///
607 /// Arrays of sizes from 1 to 12 (inclusive) implement [`From<Tuple>`], where `Tuple`
608 /// is a homogenous [prim@tuple] of appropriate length.
609 ///
610 /// Arrays coerce to [slices (`[T]`)][slice], so a slice method may be called on
611 /// an array. Indeed, this provides most of the API for working with arrays.
612 ///
613 /// Slices have a dynamic size and do not coerce to arrays. Instead, use
614 /// `slice.try_into().unwrap()` or `<ArrayType>::try_from(slice).unwrap()`.
615 ///
616 /// Array's `try_from(slice)` implementations (and the corresponding `slice.try_into()`
617 /// array implementations) succeed if the input slice length is the same as the result
618 /// array length. They optimize especially well when the optimizer can easily determine
619 /// the slice length, e.g. `<[u8; 4]>::try_from(&slice[4..8]).unwrap()`. Array implements
620 /// [TryFrom](crate::std::convert::TryFrom) returning:
621 ///
622 /// - `[T; N]` copies from the slice's elements
623 /// - `&[T; N]` references the original slice's elements
624 /// - `&mut [T; N]` references the original slice's elements
625 ///
626 /// You can move elements out of an array with a [slice pattern]. If you want
627 /// one element, see [`mem::replace`].
628 ///
629 /// # Examples
630 ///
631 /// ```
632 /// let mut array: [i32; 3] = [0; 3];
633 ///
634 /// array[1] = 1;
635 /// array[2] = 2;
636 ///
637 /// assert_eq!([1, 2], &array[1..]);
638 ///
639 /// // This loop prints: 0 1 2
640 /// for x in array {
641 ///     print!("{x} ");
642 /// }
643 /// ```
644 ///
645 /// You can also iterate over reference to the array's elements:
646 ///
647 /// ```
648 /// let array: [i32; 3] = [0; 3];
649 ///
650 /// for x in &array { }
651 /// ```
652 ///
653 /// You can use `<ArrayType>::try_from(slice)` or `slice.try_into()` to get an array from
654 /// a slice:
655 ///
656 /// ```
657 /// let bytes: [u8; 3] = [1, 0, 2];
658 /// assert_eq!(1, u16::from_le_bytes(<[u8; 2]>::try_from(&bytes[0..2]).unwrap()));
659 /// assert_eq!(512, u16::from_le_bytes(bytes[1..3].try_into().unwrap()));
660 /// ```
661 ///
662 /// You can use a [slice pattern] to move elements out of an array:
663 ///
664 /// ```
665 /// fn move_away(_: String) { /* Do interesting things. */ }
666 ///
667 /// let [john, roa] = ["John".to_string(), "Roa".to_string()];
668 /// move_away(john);
669 /// move_away(roa);
670 /// ```
671 ///
672 /// Arrays can be created from homogenous tuples of appropriate length:
673 ///
674 /// ```
675 /// let tuple: (u32, u32, u32) = (1, 2, 3);
676 /// let array: [u32; 3] = tuple.into();
677 /// ```
678 ///
679 /// # Editions
680 ///
681 /// Prior to Rust 1.53, arrays did not implement [`IntoIterator`] by value, so the method call
682 /// `array.into_iter()` auto-referenced into a [slice iterator](slice::iter). Right now, the old
683 /// behavior is preserved in the 2015 and 2018 editions of Rust for compatibility, ignoring
684 /// [`IntoIterator`] by value. In the future, the behavior on the 2015 and 2018 edition
685 /// might be made consistent to the behavior of later editions.
686 ///
687 /// ```rust,edition2018
688 /// // Rust 2015 and 2018:
689 ///
690 /// # #![allow(array_into_iter)] // override our `deny(warnings)`
691 /// let array: [i32; 3] = [0; 3];
692 ///
693 /// // This creates a slice iterator, producing references to each value.
694 /// for item in array.into_iter().enumerate() {
695 ///     let (i, x): (usize, &i32) = item;
696 ///     println!("array[{i}] = {x}");
697 /// }
698 ///
699 /// // The `array_into_iter` lint suggests this change for future compatibility:
700 /// for item in array.iter().enumerate() {
701 ///     let (i, x): (usize, &i32) = item;
702 ///     println!("array[{i}] = {x}");
703 /// }
704 ///
705 /// // You can explicitly iterate an array by value using `IntoIterator::into_iter`
706 /// for item in IntoIterator::into_iter(array).enumerate() {
707 ///     let (i, x): (usize, i32) = item;
708 ///     println!("array[{i}] = {x}");
709 /// }
710 /// ```
711 ///
712 /// Starting in the 2021 edition, `array.into_iter()` uses `IntoIterator` normally to iterate
713 /// by value, and `iter()` should be used to iterate by reference like previous editions.
714 ///
715 /// ```rust,edition2021
716 /// // Rust 2021:
717 ///
718 /// let array: [i32; 3] = [0; 3];
719 ///
720 /// // This iterates by reference:
721 /// for item in array.iter().enumerate() {
722 ///     let (i, x): (usize, &i32) = item;
723 ///     println!("array[{i}] = {x}");
724 /// }
725 ///
726 /// // This iterates by value:
727 /// for item in array.into_iter().enumerate() {
728 ///     let (i, x): (usize, i32) = item;
729 ///     println!("array[{i}] = {x}");
730 /// }
731 /// ```
732 ///
733 /// Future language versions might start treating the `array.into_iter()`
734 /// syntax on editions 2015 and 2018 the same as on edition 2021. So code using
735 /// those older editions should still be written with this change in mind, to
736 /// prevent breakage in the future. The safest way to accomplish this is to
737 /// avoid the `into_iter` syntax on those editions. If an edition update is not
738 /// viable/desired, there are multiple alternatives:
739 /// * use `iter`, equivalent to the old behavior, creating references
740 /// * use [`IntoIterator::into_iter`], equivalent to the post-2021 behavior (Rust 1.53+)
741 /// * replace `for ... in array.into_iter() {` with `for ... in array {`,
742 ///   equivalent to the post-2021 behavior (Rust 1.53+)
743 ///
744 /// ```rust,edition2018
745 /// // Rust 2015 and 2018:
746 ///
747 /// let array: [i32; 3] = [0; 3];
748 ///
749 /// // This iterates by reference:
750 /// for item in array.iter() {
751 ///     let x: &i32 = item;
752 ///     println!("{x}");
753 /// }
754 ///
755 /// // This iterates by value:
756 /// for item in IntoIterator::into_iter(array) {
757 ///     let x: i32 = item;
758 ///     println!("{x}");
759 /// }
760 ///
761 /// // This iterates by value:
762 /// for item in array {
763 ///     let x: i32 = item;
764 ///     println!("{x}");
765 /// }
766 ///
767 /// // IntoIter can also start a chain.
768 /// // This iterates by value:
769 /// for item in IntoIterator::into_iter(array).enumerate() {
770 ///     let (i, x): (usize, i32) = item;
771 ///     println!("array[{i}] = {x}");
772 /// }
773 /// ```
774 ///
775 /// [slice]: prim@slice
776 /// [`Debug`]: fmt::Debug
777 /// [`Hash`]: hash::Hash
778 /// [`Borrow`]: borrow::Borrow
779 /// [`BorrowMut`]: borrow::BorrowMut
780 /// [slice pattern]: ../reference/patterns.html#slice-patterns
781 /// [`From<Tuple>`]: convert::From
782 mod prim_array {}
783 
784 #[rustc_doc_primitive = "slice"]
785 #[doc(alias = "[")]
786 #[doc(alias = "]")]
787 #[doc(alias = "[]")]
788 /// A dynamically-sized view into a contiguous sequence, `[T]`. Contiguous here
789 /// means that elements are laid out so that every element is the same
790 /// distance from its neighbors.
791 ///
792 /// *[See also the `std::slice` module](crate::std::slice).*
793 ///
794 /// Slices are a view into a block of memory represented as a pointer and a
795 /// length.
796 ///
797 /// ```
798 /// // slicing a Vec
799 /// let vec = vec![1, 2, 3];
800 /// let int_slice = &vec[..];
801 /// // coercing an array to a slice
802 /// let str_slice: &[&str] = &["one", "two", "three"];
803 /// ```
804 ///
805 /// Slices are either mutable or shared. The shared slice type is `&[T]`,
806 /// while the mutable slice type is `&mut [T]`, where `T` represents the element
807 /// type. For example, you can mutate the block of memory that a mutable slice
808 /// points to:
809 ///
810 /// ```
811 /// let mut x = [1, 2, 3];
812 /// let x = &mut x[..]; // Take a full slice of `x`.
813 /// x[1] = 7;
814 /// assert_eq!(x, &[1, 7, 3]);
815 /// ```
816 ///
817 /// As slices store the length of the sequence they refer to, they have twice
818 /// the size of pointers to [`Sized`](marker/trait.Sized.html) types.
819 /// Also see the reference on
820 /// [dynamically sized types](../reference/dynamically-sized-types.html).
821 ///
822 /// ```
823 /// # use std::rc::Rc;
824 /// let pointer_size = std::mem::size_of::<&u8>();
825 /// assert_eq!(2 * pointer_size, std::mem::size_of::<&[u8]>());
826 /// assert_eq!(2 * pointer_size, std::mem::size_of::<*const [u8]>());
827 /// assert_eq!(2 * pointer_size, std::mem::size_of::<Box<[u8]>>());
828 /// assert_eq!(2 * pointer_size, std::mem::size_of::<Rc<[u8]>>());
829 /// ```
830 ///
831 /// ## Trait Implementations
832 ///
833 /// Some traits are implemented for slices if the element type implements
834 /// that trait. This includes [`Eq`], [`Hash`] and [`Ord`].
835 ///
836 /// ## Iteration
837 ///
838 /// The slices implement `IntoIterator`. The iterator yields references to the
839 /// slice elements.
840 ///
841 /// ```
842 /// let numbers: &[i32] = &[0, 1, 2];
843 /// for n in numbers {
844 ///     println!("{n} is a number!");
845 /// }
846 /// ```
847 ///
848 /// The mutable slice yields mutable references to the elements:
849 ///
850 /// ```
851 /// let mut scores: &mut [i32] = &mut [7, 8, 9];
852 /// for score in scores {
853 ///     *score += 1;
854 /// }
855 /// ```
856 ///
857 /// This iterator yields mutable references to the slice's elements, so while
858 /// the element type of the slice is `i32`, the element type of the iterator is
859 /// `&mut i32`.
860 ///
861 /// * [`.iter`] and [`.iter_mut`] are the explicit methods to return the default
862 ///   iterators.
863 /// * Further methods that return iterators are [`.split`], [`.splitn`],
864 ///   [`.chunks`], [`.windows`] and more.
865 ///
866 /// [`Hash`]: core::hash::Hash
867 /// [`.iter`]: slice::iter
868 /// [`.iter_mut`]: slice::iter_mut
869 /// [`.split`]: slice::split
870 /// [`.splitn`]: slice::splitn
871 /// [`.chunks`]: slice::chunks
872 /// [`.windows`]: slice::windows
873 mod prim_slice {}
874 
875 #[rustc_doc_primitive = "str"]
876 /// String slices.
877 ///
878 /// *[See also the `std::str` module](crate::std::str).*
879 ///
880 /// The `str` type, also called a 'string slice', is the most primitive string
881 /// type. It is usually seen in its borrowed form, `&str`. It is also the type
882 /// of string literals, `&'static str`.
883 ///
884 /// String slices are always valid UTF-8.
885 ///
886 /// # Basic Usage
887 ///
888 /// String literals are string slices:
889 ///
890 /// ```
891 /// let hello_world = "Hello, World!";
892 /// ```
893 ///
894 /// Here we have declared a string slice initialized with a string literal.
895 /// String literals have a static lifetime, which means the string `hello_world`
896 /// is guaranteed to be valid for the duration of the entire program.
897 /// We can explicitly specify `hello_world`'s lifetime as well:
898 ///
899 /// ```
900 /// let hello_world: &'static str = "Hello, world!";
901 /// ```
902 ///
903 /// # Representation
904 ///
905 /// A `&str` is made up of two components: a pointer to some bytes, and a
906 /// length. You can look at these with the [`as_ptr`] and [`len`] methods:
907 ///
908 /// ```
909 /// use std::slice;
910 /// use std::str;
911 ///
912 /// let story = "Once upon a time...";
913 ///
914 /// let ptr = story.as_ptr();
915 /// let len = story.len();
916 ///
917 /// // story has nineteen bytes
918 /// assert_eq!(19, len);
919 ///
920 /// // We can re-build a str out of ptr and len. This is all unsafe because
921 /// // we are responsible for making sure the two components are valid:
922 /// let s = unsafe {
923 ///     // First, we build a &[u8]...
924 ///     let slice = slice::from_raw_parts(ptr, len);
925 ///
926 ///     // ... and then convert that slice into a string slice
927 ///     str::from_utf8(slice)
928 /// };
929 ///
930 /// assert_eq!(s, Ok(story));
931 /// ```
932 ///
933 /// [`as_ptr`]: str::as_ptr
934 /// [`len`]: str::len
935 ///
936 /// Note: This example shows the internals of `&str`. `unsafe` should not be
937 /// used to get a string slice under normal circumstances. Use `as_str`
938 /// instead.
939 mod prim_str {}
940 
941 #[rustc_doc_primitive = "tuple"]
942 #[doc(alias = "(")]
943 #[doc(alias = ")")]
944 #[doc(alias = "()")]
945 //
946 /// A finite heterogeneous sequence, `(T, U, ..)`.
947 ///
948 /// Let's cover each of those in turn:
949 ///
950 /// Tuples are *finite*. In other words, a tuple has a length. Here's a tuple
951 /// of length `3`:
952 ///
953 /// ```
954 /// ("hello", 5, 'c');
955 /// ```
956 ///
957 /// 'Length' is also sometimes called 'arity' here; each tuple of a different
958 /// length is a different, distinct type.
959 ///
960 /// Tuples are *heterogeneous*. This means that each element of the tuple can
961 /// have a different type. In that tuple above, it has the type:
962 ///
963 /// ```
964 /// # let _:
965 /// (&'static str, i32, char)
966 /// # = ("hello", 5, 'c');
967 /// ```
968 ///
969 /// Tuples are a *sequence*. This means that they can be accessed by position;
970 /// this is called 'tuple indexing', and it looks like this:
971 ///
972 /// ```rust
973 /// let tuple = ("hello", 5, 'c');
974 ///
975 /// assert_eq!(tuple.0, "hello");
976 /// assert_eq!(tuple.1, 5);
977 /// assert_eq!(tuple.2, 'c');
978 /// ```
979 ///
980 /// The sequential nature of the tuple applies to its implementations of various
981 /// traits. For example, in [`PartialOrd`] and [`Ord`], the elements are compared
982 /// sequentially until the first non-equal set is found.
983 ///
984 /// For more about tuples, see [the book](../book/ch03-02-data-types.html#the-tuple-type).
985 ///
986 // Hardcoded anchor in src/librustdoc/html/format.rs
987 // linked to as `#trait-implementations-1`
988 /// # Trait implementations
989 ///
990 /// In this documentation the shorthand `(T₁, T₂, …, Tₙ)` is used to represent tuples of varying
991 /// length. When that is used, any trait bound expressed on `T` applies to each element of the
992 /// tuple independently. Note that this is a convenience notation to avoid repetitive
993 /// documentation, not valid Rust syntax.
994 ///
995 /// Due to a temporary restriction in Rust’s type system, the following traits are only
996 /// implemented on tuples of arity 12 or less. In the future, this may change:
997 ///
998 /// * [`PartialEq`]
999 /// * [`Eq`]
1000 /// * [`PartialOrd`]
1001 /// * [`Ord`]
1002 /// * [`Debug`]
1003 /// * [`Default`]
1004 /// * [`Hash`]
1005 /// * [`From<[T; N]>`][from]
1006 ///
1007 /// [from]: convert::From
1008 /// [`Debug`]: fmt::Debug
1009 /// [`Hash`]: hash::Hash
1010 ///
1011 /// The following traits are implemented for tuples of any length. These traits have
1012 /// implementations that are automatically generated by the compiler, so are not limited by
1013 /// missing language features.
1014 ///
1015 /// * [`Clone`]
1016 /// * [`Copy`]
1017 /// * [`Send`]
1018 /// * [`Sync`]
1019 /// * [`Unpin`]
1020 /// * [`UnwindSafe`]
1021 /// * [`RefUnwindSafe`]
1022 ///
1023 /// [`UnwindSafe`]: panic::UnwindSafe
1024 /// [`RefUnwindSafe`]: panic::RefUnwindSafe
1025 ///
1026 /// # Examples
1027 ///
1028 /// Basic usage:
1029 ///
1030 /// ```
1031 /// let tuple = ("hello", 5, 'c');
1032 ///
1033 /// assert_eq!(tuple.0, "hello");
1034 /// ```
1035 ///
1036 /// Tuples are often used as a return type when you want to return more than
1037 /// one value:
1038 ///
1039 /// ```
1040 /// fn calculate_point() -> (i32, i32) {
1041 ///     // Don't do a calculation, that's not the point of the example
1042 ///     (4, 5)
1043 /// }
1044 ///
1045 /// let point = calculate_point();
1046 ///
1047 /// assert_eq!(point.0, 4);
1048 /// assert_eq!(point.1, 5);
1049 ///
1050 /// // Combining this with patterns can be nicer.
1051 ///
1052 /// let (x, y) = calculate_point();
1053 ///
1054 /// assert_eq!(x, 4);
1055 /// assert_eq!(y, 5);
1056 /// ```
1057 ///
1058 /// Homogenous tuples can be created from arrays of appropriate length:
1059 ///
1060 /// ```
1061 /// let array: [u32; 3] = [1, 2, 3];
1062 /// let tuple: (u32, u32, u32) = array.into();
1063 /// ```
1064 ///
1065 mod prim_tuple {}
1066 
1067 // Required to make auto trait impls render.
1068 // See src/librustdoc/passes/collect_trait_impls.rs:collect_trait_impls
1069 #[doc(hidden)]
1070 impl<T> (T,) {}
1071 
1072 // Fake impl that's only really used for docs.
1073 #[cfg(doc)]
1074 #[doc(fake_variadic)]
1075 /// This trait is implemented on arbitrary-length tuples.
1076 impl<T: Clone> Clone for (T,) {
clone(&self) -> Self1077     fn clone(&self) -> Self {
1078         loop {}
1079     }
1080 }
1081 
1082 // Fake impl that's only really used for docs.
1083 #[cfg(doc)]
1084 #[doc(fake_variadic)]
1085 /// This trait is implemented on arbitrary-length tuples.
1086 impl<T: Copy> Copy for (T,) {
1087     // empty
1088 }
1089 
1090 #[rustc_doc_primitive = "f32"]
1091 /// A 32-bit floating point type (specifically, the "binary32" type defined in IEEE 754-2008).
1092 ///
1093 /// This type can represent a wide range of decimal numbers, like `3.5`, `27`,
1094 /// `-113.75`, `0.0078125`, `34359738368`, `0`, `-1`. So unlike integer types
1095 /// (such as `i32`), floating point types can represent non-integer numbers,
1096 /// too.
1097 ///
1098 /// However, being able to represent this wide range of numbers comes at the
1099 /// cost of precision: floats can only represent some of the real numbers and
1100 /// calculation with floats round to a nearby representable number. For example,
1101 /// `5.0` and `1.0` can be exactly represented as `f32`, but `1.0 / 5.0` results
1102 /// in `0.20000000298023223876953125` since `0.2` cannot be exactly represented
1103 /// as `f32`. Note, however, that printing floats with `println` and friends will
1104 /// often discard insignificant digits: `println!("{}", 1.0f32 / 5.0f32)` will
1105 /// print `0.2`.
1106 ///
1107 /// Additionally, `f32` can represent some special values:
1108 ///
1109 /// - −0.0: IEEE 754 floating point numbers have a bit that indicates their sign, so −0.0 is a
1110 ///   possible value. For comparison −0.0 = +0.0, but floating point operations can carry
1111 ///   the sign bit through arithmetic operations. This means −0.0 × +0.0 produces −0.0 and
1112 ///   a negative number rounded to a value smaller than a float can represent also produces −0.0.
1113 /// - [∞](#associatedconstant.INFINITY) and
1114 ///   [−∞](#associatedconstant.NEG_INFINITY): these result from calculations
1115 ///   like `1.0 / 0.0`.
1116 /// - [NaN (not a number)](#associatedconstant.NAN): this value results from
1117 ///   calculations like `(-1.0).sqrt()`. NaN has some potentially unexpected
1118 ///   behavior:
1119 ///   - It is not equal to any float, including itself! This is the reason `f32`
1120 ///     doesn't implement the `Eq` trait.
1121 ///   - It is also neither smaller nor greater than any float, making it
1122 ///     impossible to sort by the default comparison operation, which is the
1123 ///     reason `f32` doesn't implement the `Ord` trait.
1124 ///   - It is also considered *infectious* as almost all calculations where one
1125 ///     of the operands is NaN will also result in NaN. The explanations on this
1126 ///     page only explicitly document behavior on NaN operands if this default
1127 ///     is deviated from.
1128 ///   - Lastly, there are multiple bit patterns that are considered NaN.
1129 ///     Rust does not currently guarantee that the bit patterns of NaN are
1130 ///     preserved over arithmetic operations, and they are not guaranteed to be
1131 ///     portable or even fully deterministic! This means that there may be some
1132 ///     surprising results upon inspecting the bit patterns,
1133 ///     as the same calculations might produce NaNs with different bit patterns.
1134 ///
1135 /// When the number resulting from a primitive operation (addition,
1136 /// subtraction, multiplication, or division) on this type is not exactly
1137 /// representable as `f32`, it is rounded according to the roundTiesToEven
1138 /// direction defined in IEEE 754-2008. That means:
1139 ///
1140 /// - The result is the representable value closest to the true value, if there
1141 ///   is a unique closest representable value.
1142 /// - If the true value is exactly half-way between two representable values,
1143 ///   the result is the one with an even least-significant binary digit.
1144 /// - If the true value's magnitude is ≥ `f32::MAX` + 2<sup>(`f32::MAX_EXP` −
1145 ///   `f32::MANTISSA_DIGITS` − 1)</sup>, the result is ∞ or −∞ (preserving the
1146 ///   true value's sign).
1147 ///
1148 /// For more information on floating point numbers, see [Wikipedia][wikipedia].
1149 ///
1150 /// *[See also the `std::f32::consts` module](crate::std::f32::consts).*
1151 ///
1152 /// [wikipedia]: https://en.wikipedia.org/wiki/Single-precision_floating-point_format
1153 mod prim_f32 {}
1154 
1155 #[rustc_doc_primitive = "f64"]
1156 /// A 64-bit floating point type (specifically, the "binary64" type defined in IEEE 754-2008).
1157 ///
1158 /// This type is very similar to [`f32`], but has increased
1159 /// precision by using twice as many bits. Please see [the documentation for
1160 /// `f32`][`f32`] or [Wikipedia on double precision
1161 /// values][wikipedia] for more information.
1162 ///
1163 /// *[See also the `std::f64::consts` module](crate::std::f64::consts).*
1164 ///
1165 /// [`f32`]: prim@f32
1166 /// [wikipedia]: https://en.wikipedia.org/wiki/Double-precision_floating-point_format
1167 mod prim_f64 {}
1168 
1169 #[rustc_doc_primitive = "i8"]
1170 //
1171 /// The 8-bit signed integer type.
1172 mod prim_i8 {}
1173 
1174 #[rustc_doc_primitive = "i16"]
1175 //
1176 /// The 16-bit signed integer type.
1177 mod prim_i16 {}
1178 
1179 #[rustc_doc_primitive = "i32"]
1180 //
1181 /// The 32-bit signed integer type.
1182 mod prim_i32 {}
1183 
1184 #[rustc_doc_primitive = "i64"]
1185 //
1186 /// The 64-bit signed integer type.
1187 mod prim_i64 {}
1188 
1189 #[rustc_doc_primitive = "i128"]
1190 //
1191 /// The 128-bit signed integer type.
1192 mod prim_i128 {}
1193 
1194 #[rustc_doc_primitive = "u8"]
1195 //
1196 /// The 8-bit unsigned integer type.
1197 mod prim_u8 {}
1198 
1199 #[rustc_doc_primitive = "u16"]
1200 //
1201 /// The 16-bit unsigned integer type.
1202 mod prim_u16 {}
1203 
1204 #[rustc_doc_primitive = "u32"]
1205 //
1206 /// The 32-bit unsigned integer type.
1207 mod prim_u32 {}
1208 
1209 #[rustc_doc_primitive = "u64"]
1210 //
1211 /// The 64-bit unsigned integer type.
1212 mod prim_u64 {}
1213 
1214 #[rustc_doc_primitive = "u128"]
1215 //
1216 /// The 128-bit unsigned integer type.
1217 mod prim_u128 {}
1218 
1219 #[rustc_doc_primitive = "isize"]
1220 //
1221 /// The pointer-sized signed integer type.
1222 ///
1223 /// The size of this primitive is how many bytes it takes to reference any
1224 /// location in memory. For example, on a 32 bit target, this is 4 bytes
1225 /// and on a 64 bit target, this is 8 bytes.
1226 mod prim_isize {}
1227 
1228 #[rustc_doc_primitive = "usize"]
1229 //
1230 /// The pointer-sized unsigned integer type.
1231 ///
1232 /// The size of this primitive is how many bytes it takes to reference any
1233 /// location in memory. For example, on a 32 bit target, this is 4 bytes
1234 /// and on a 64 bit target, this is 8 bytes.
1235 mod prim_usize {}
1236 
1237 #[rustc_doc_primitive = "reference"]
1238 #[doc(alias = "&")]
1239 #[doc(alias = "&mut")]
1240 //
1241 /// References, `&T` and `&mut T`.
1242 ///
1243 /// A reference represents a borrow of some owned value. You can get one by using the `&` or `&mut`
1244 /// operators on a value, or by using a [`ref`](../std/keyword.ref.html) or
1245 /// <code>[ref](../std/keyword.ref.html) [mut](../std/keyword.mut.html)</code> pattern.
1246 ///
1247 /// For those familiar with pointers, a reference is just a pointer that is assumed to be
1248 /// aligned, not null, and pointing to memory containing a valid value of `T` - for example,
1249 /// <code>&[bool]</code> can only point to an allocation containing the integer values `1`
1250 /// ([`true`](../std/keyword.true.html)) or `0` ([`false`](../std/keyword.false.html)), but
1251 /// creating a <code>&[bool]</code> that points to an allocation containing
1252 /// the value `3` causes undefined behaviour.
1253 /// In fact, <code>[Option]\<&T></code> has the same memory representation as a
1254 /// nullable but aligned pointer, and can be passed across FFI boundaries as such.
1255 ///
1256 /// In most cases, references can be used much like the original value. Field access, method
1257 /// calling, and indexing work the same (save for mutability rules, of course). In addition, the
1258 /// comparison operators transparently defer to the referent's implementation, allowing references
1259 /// to be compared the same as owned values.
1260 ///
1261 /// References have a lifetime attached to them, which represents the scope for which the borrow is
1262 /// valid. A lifetime is said to "outlive" another one if its representative scope is as long or
1263 /// longer than the other. The `'static` lifetime is the longest lifetime, which represents the
1264 /// total life of the program. For example, string literals have a `'static` lifetime because the
1265 /// text data is embedded into the binary of the program, rather than in an allocation that needs
1266 /// to be dynamically managed.
1267 ///
1268 /// `&mut T` references can be freely coerced into `&T` references with the same referent type, and
1269 /// references with longer lifetimes can be freely coerced into references with shorter ones.
1270 ///
1271 /// Reference equality by address, instead of comparing the values pointed to, is accomplished via
1272 /// implicit reference-pointer coercion and raw pointer equality via [`ptr::eq`], while
1273 /// [`PartialEq`] compares values.
1274 ///
1275 /// ```
1276 /// use std::ptr;
1277 ///
1278 /// let five = 5;
1279 /// let other_five = 5;
1280 /// let five_ref = &five;
1281 /// let same_five_ref = &five;
1282 /// let other_five_ref = &other_five;
1283 ///
1284 /// assert!(five_ref == same_five_ref);
1285 /// assert!(five_ref == other_five_ref);
1286 ///
1287 /// assert!(ptr::eq(five_ref, same_five_ref));
1288 /// assert!(!ptr::eq(five_ref, other_five_ref));
1289 /// ```
1290 ///
1291 /// For more information on how to use references, see [the book's section on "References and
1292 /// Borrowing"][book-refs].
1293 ///
1294 /// [book-refs]: ../book/ch04-02-references-and-borrowing.html
1295 ///
1296 /// # Trait implementations
1297 ///
1298 /// The following traits are implemented for all `&T`, regardless of the type of its referent:
1299 ///
1300 /// * [`Copy`]
1301 /// * [`Clone`] \(Note that this will not defer to `T`'s `Clone` implementation if it exists!)
1302 /// * [`Deref`]
1303 /// * [`Borrow`]
1304 /// * [`fmt::Pointer`]
1305 ///
1306 /// [`Deref`]: ops::Deref
1307 /// [`Borrow`]: borrow::Borrow
1308 ///
1309 /// `&mut T` references get all of the above except `Copy` and `Clone` (to prevent creating
1310 /// multiple simultaneous mutable borrows), plus the following, regardless of the type of its
1311 /// referent:
1312 ///
1313 /// * [`DerefMut`]
1314 /// * [`BorrowMut`]
1315 ///
1316 /// [`DerefMut`]: ops::DerefMut
1317 /// [`BorrowMut`]: borrow::BorrowMut
1318 /// [bool]: prim@bool
1319 ///
1320 /// The following traits are implemented on `&T` references if the underlying `T` also implements
1321 /// that trait:
1322 ///
1323 /// * All the traits in [`std::fmt`] except [`fmt::Pointer`] (which is implemented regardless of the type of its referent) and [`fmt::Write`]
1324 /// * [`PartialOrd`]
1325 /// * [`Ord`]
1326 /// * [`PartialEq`]
1327 /// * [`Eq`]
1328 /// * [`AsRef`]
1329 /// * [`Fn`] \(in addition, `&T` references get [`FnMut`] and [`FnOnce`] if `T: Fn`)
1330 /// * [`Hash`]
1331 /// * [`ToSocketAddrs`]
1332 /// * [`Send`] \(`&T` references also require <code>T: [Sync]</code>)
1333 /// * [`Sync`]
1334 ///
1335 /// [`std::fmt`]: fmt
1336 /// [`Hash`]: hash::Hash
1337 //#[doc = concat!("[`ToSocketAddrs`]: ", include_str!("../primitive_docs/net_tosocketaddrs.md"))]
1338 ///
1339 /// `&mut T` references get all of the above except `ToSocketAddrs`, plus the following, if `T`
1340 /// implements that trait:
1341 ///
1342 /// * [`AsMut`]
1343 /// * [`FnMut`] \(in addition, `&mut T` references get [`FnOnce`] if `T: FnMut`)
1344 /// * [`fmt::Write`]
1345 /// * [`Iterator`]
1346 /// * [`DoubleEndedIterator`]
1347 /// * [`ExactSizeIterator`]
1348 /// * [`FusedIterator`]
1349 /// * [`TrustedLen`]
1350 /// * [`io::Write`]
1351 /// * [`Read`]
1352 /// * [`Seek`]
1353 /// * [`BufRead`]
1354 ///
1355 /// [`FusedIterator`]: iter::FusedIterator
1356 /// [`TrustedLen`]: iter::TrustedLen
1357 // #[doc = concat!("[`Seek`]: ", include_str!("../primitive_docs/io_seek.md"))]
1358 // #[doc = concat!("[`BufRead`]: ", include_str!("../primitive_docs/io_bufread.md"))]
1359 // #[doc = concat!("[`Read`]: ", include_str!("../primitive_docs/io_read.md"))]
1360 // #[doc = concat!("[`io::Write`]: ", include_str!("../primitive_docs/io_write.md"))]
1361 ///
1362 /// Note that due to method call deref coercion, simply calling a trait method will act like they
1363 /// work on references as well as they do on owned values! The implementations described here are
1364 /// meant for generic contexts, where the final type `T` is a type parameter or otherwise not
1365 /// locally known.
1366 mod prim_ref {}
1367 
1368 #[rustc_doc_primitive = "fn"]
1369 //
1370 /// Function pointers, like `fn(usize) -> bool`.
1371 ///
1372 /// *See also the traits [`Fn`], [`FnMut`], and [`FnOnce`].*
1373 ///
1374 /// Function pointers are pointers that point to *code*, not data. They can be called
1375 /// just like functions. Like references, function pointers are, among other things, assumed to
1376 /// not be null, so if you want to pass a function pointer over FFI and be able to accommodate null
1377 /// pointers, make your type [`Option<fn()>`](core::option#options-and-pointers-nullable-pointers)
1378 /// with your required signature.
1379 ///
1380 /// ### Safety
1381 ///
1382 /// Plain function pointers are obtained by casting either plain functions, or closures that don't
1383 /// capture an environment:
1384 ///
1385 /// ```
1386 /// fn add_one(x: usize) -> usize {
1387 ///     x + 1
1388 /// }
1389 ///
1390 /// let ptr: fn(usize) -> usize = add_one;
1391 /// assert_eq!(ptr(5), 6);
1392 ///
1393 /// let clos: fn(usize) -> usize = |x| x + 5;
1394 /// assert_eq!(clos(5), 10);
1395 /// ```
1396 ///
1397 /// In addition to varying based on their signature, function pointers come in two flavors: safe
1398 /// and unsafe. Plain `fn()` function pointers can only point to safe functions,
1399 /// while `unsafe fn()` function pointers can point to safe or unsafe functions.
1400 ///
1401 /// ```
1402 /// fn add_one(x: usize) -> usize {
1403 ///     x + 1
1404 /// }
1405 ///
1406 /// unsafe fn add_one_unsafely(x: usize) -> usize {
1407 ///     x + 1
1408 /// }
1409 ///
1410 /// let safe_ptr: fn(usize) -> usize = add_one;
1411 ///
1412 /// //ERROR: mismatched types: expected normal fn, found unsafe fn
1413 /// //let bad_ptr: fn(usize) -> usize = add_one_unsafely;
1414 ///
1415 /// let unsafe_ptr: unsafe fn(usize) -> usize = add_one_unsafely;
1416 /// let really_safe_ptr: unsafe fn(usize) -> usize = add_one;
1417 /// ```
1418 ///
1419 /// ### ABI
1420 ///
1421 /// On top of that, function pointers can vary based on what ABI they use. This
1422 /// is achieved by adding the `extern` keyword before the type, followed by the
1423 /// ABI in question. The default ABI is "Rust", i.e., `fn()` is the exact same
1424 /// type as `extern "Rust" fn()`. A pointer to a function with C ABI would have
1425 /// type `extern "C" fn()`.
1426 ///
1427 /// `extern "ABI" { ... }` blocks declare functions with ABI "ABI". The default
1428 /// here is "C", i.e., functions declared in an `extern {...}` block have "C"
1429 /// ABI.
1430 ///
1431 /// For more information and a list of supported ABIs, see [the nomicon's
1432 /// section on foreign calling conventions][nomicon-abi].
1433 ///
1434 /// [nomicon-abi]: ../nomicon/ffi.html#foreign-calling-conventions
1435 ///
1436 /// ### Variadic functions
1437 ///
1438 /// Extern function declarations with the "C" or "cdecl" ABIs can also be *variadic*, allowing them
1439 /// to be called with a variable number of arguments. Normal Rust functions, even those with an
1440 /// `extern "ABI"`, cannot be variadic. For more information, see [the nomicon's section on
1441 /// variadic functions][nomicon-variadic].
1442 ///
1443 /// [nomicon-variadic]: ../nomicon/ffi.html#variadic-functions
1444 ///
1445 /// ### Creating function pointers
1446 ///
1447 /// When `bar` is the name of a function, then the expression `bar` is *not* a
1448 /// function pointer. Rather, it denotes a value of an unnameable type that
1449 /// uniquely identifies the function `bar`. The value is zero-sized because the
1450 /// type already identifies the function. This has the advantage that "calling"
1451 /// the value (it implements the `Fn*` traits) does not require dynamic
1452 /// dispatch.
1453 ///
1454 /// This zero-sized type *coerces* to a regular function pointer. For example:
1455 ///
1456 /// ```rust
1457 /// use std::mem;
1458 ///
1459 /// fn bar(x: i32) {}
1460 ///
1461 /// let not_bar_ptr = bar; // `not_bar_ptr` is zero-sized, uniquely identifying `bar`
1462 /// assert_eq!(mem::size_of_val(&not_bar_ptr), 0);
1463 ///
1464 /// let bar_ptr: fn(i32) = not_bar_ptr; // force coercion to function pointer
1465 /// assert_eq!(mem::size_of_val(&bar_ptr), mem::size_of::<usize>());
1466 ///
1467 /// let footgun = &bar; // this is a shared reference to the zero-sized type identifying `bar`
1468 /// ```
1469 ///
1470 /// The last line shows that `&bar` is not a function pointer either. Rather, it
1471 /// is a reference to the function-specific ZST. `&bar` is basically never what you
1472 /// want when `bar` is a function.
1473 ///
1474 /// ### Casting to and from integers
1475 ///
1476 /// You cast function pointers directly to integers:
1477 ///
1478 /// ```rust
1479 /// let fnptr: fn(i32) -> i32 = |x| x+2;
1480 /// let fnptr_addr = fnptr as usize;
1481 /// ```
1482 ///
1483 /// However, a direct cast back is not possible. You need to use `transmute`:
1484 ///
1485 /// ```rust
1486 /// # #[cfg(not(miri))] { // FIXME: use strict provenance APIs once they are stable, then remove this `cfg`
1487 /// # let fnptr: fn(i32) -> i32 = |x| x+2;
1488 /// # let fnptr_addr = fnptr as usize;
1489 /// let fnptr = fnptr_addr as *const ();
1490 /// let fnptr: fn(i32) -> i32 = unsafe { std::mem::transmute(fnptr) };
1491 /// assert_eq!(fnptr(40), 42);
1492 /// # }
1493 /// ```
1494 ///
1495 /// Crucially, we `as`-cast to a raw pointer before `transmute`ing to a function pointer.
1496 /// This avoids an integer-to-pointer `transmute`, which can be problematic.
1497 /// Transmuting between raw pointers and function pointers (i.e., two pointer types) is fine.
1498 ///
1499 /// Note that all of this is not portable to platforms where function pointers and data pointers
1500 /// have different sizes.
1501 ///
1502 /// ### Trait implementations
1503 ///
1504 /// In this documentation the shorthand `fn (T₁, T₂, …, Tₙ)` is used to represent non-variadic
1505 /// function pointers of varying length. Note that this is a convenience notation to avoid
1506 /// repetitive documentation, not valid Rust syntax.
1507 ///
1508 /// Due to a temporary restriction in Rust's type system, these traits are only implemented on
1509 /// functions that take 12 arguments or less, with the `"Rust"` and `"C"` ABIs. In the future, this
1510 /// may change:
1511 ///
1512 /// * [`PartialEq`]
1513 /// * [`Eq`]
1514 /// * [`PartialOrd`]
1515 /// * [`Ord`]
1516 /// * [`Hash`]
1517 /// * [`Pointer`]
1518 /// * [`Debug`]
1519 ///
1520 /// The following traits are implemented for function pointers with any number of arguments and
1521 /// any ABI. These traits have implementations that are automatically generated by the compiler,
1522 /// so are not limited by missing language features:
1523 ///
1524 /// * [`Clone`]
1525 /// * [`Copy`]
1526 /// * [`Send`]
1527 /// * [`Sync`]
1528 /// * [`Unpin`]
1529 /// * [`UnwindSafe`]
1530 /// * [`RefUnwindSafe`]
1531 ///
1532 /// [`Hash`]: hash::Hash
1533 /// [`Pointer`]: fmt::Pointer
1534 /// [`UnwindSafe`]: panic::UnwindSafe
1535 /// [`RefUnwindSafe`]: panic::RefUnwindSafe
1536 ///
1537 /// In addition, all *safe* function pointers implement [`Fn`], [`FnMut`], and [`FnOnce`], because
1538 /// these traits are specially known to the compiler.
1539 mod prim_fn {}
1540 
1541 // Required to make auto trait impls render.
1542 // See src/librustdoc/passes/collect_trait_impls.rs:collect_trait_impls
1543 #[doc(hidden)]
1544 impl<Ret, T> fn(T) -> Ret {}
1545 
1546 // Fake impl that's only really used for docs.
1547 #[cfg(doc)]
1548 #[doc(fake_variadic)]
1549 /// This trait is implemented on function pointers with any number of arguments.
1550 impl<Ret, T> Clone for fn(T) -> Ret {
clone(&self) -> Self1551     fn clone(&self) -> Self {
1552         loop {}
1553     }
1554 }
1555 
1556 // Fake impl that's only really used for docs.
1557 #[cfg(doc)]
1558 #[doc(fake_variadic)]
1559 /// This trait is implemented on function pointers with any number of arguments.
1560 impl<Ret, T> Copy for fn(T) -> Ret {
1561     // empty
1562 }
1563