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