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