]> git.lizzy.rs Git - rust.git/blob - library/std/src/primitive_docs.rs
Merge commit 'a8385522ade6f67853edac730b5bf164ddb298fd' into simd-remove-autosplats
[rust.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 #[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 #[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 #[doc(primitive = "char")]
278 /// A character type.
279 ///
280 /// The `char` type represents a single character. More specifically, since
281 /// 'character' isn't a well-defined concept in Unicode, `char` is a '[Unicode
282 /// scalar value]', which is similar to, but not the same as, a '[Unicode code
283 /// point]'.
284 ///
285 /// [Unicode scalar value]: https://www.unicode.org/glossary/#unicode_scalar_value
286 /// [Unicode code point]: https://www.unicode.org/glossary/#code_point
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 /// # Representation
293 ///
294 /// `char` is always four bytes in size. This is a different representation than
295 /// a given character would have as part of a [`String`]. For example:
296 ///
297 /// ```
298 /// let v = vec!['h', 'e', 'l', 'l', 'o'];
299 ///
300 /// // five elements times four bytes for each element
301 /// assert_eq!(20, v.len() * std::mem::size_of::<char>());
302 ///
303 /// let s = String::from("hello");
304 ///
305 /// // five elements times one byte per element
306 /// assert_eq!(5, s.len() * std::mem::size_of::<u8>());
307 /// ```
308 ///
309 #[doc = concat!("[`String`]: ", include_str!("../primitive_docs/string_string.md"))]
310 ///
311 /// As always, remember that a human intuition for 'character' might not map to
312 /// Unicode's definitions. For example, despite looking similar, the 'é'
313 /// character is one Unicode code point while 'é' is two Unicode code points:
314 ///
315 /// ```
316 /// let mut chars = "é".chars();
317 /// // U+00e9: 'latin small letter e with acute'
318 /// assert_eq!(Some('\u{00e9}'), chars.next());
319 /// assert_eq!(None, chars.next());
320 ///
321 /// let mut chars = "é".chars();
322 /// // U+0065: 'latin small letter e'
323 /// assert_eq!(Some('\u{0065}'), chars.next());
324 /// // U+0301: 'combining acute accent'
325 /// assert_eq!(Some('\u{0301}'), chars.next());
326 /// assert_eq!(None, chars.next());
327 /// ```
328 ///
329 /// This means that the contents of the first string above _will_ fit into a
330 /// `char` while the contents of the second string _will not_. Trying to create
331 /// a `char` literal with the contents of the second string gives an error:
332 ///
333 /// ```text
334 /// error: character literal may only contain one codepoint: 'é'
335 /// let c = 'é';
336 ///         ^^^
337 /// ```
338 ///
339 /// Another implication of the 4-byte fixed size of a `char` is that
340 /// per-`char` processing can end up using a lot more memory:
341 ///
342 /// ```
343 /// let s = String::from("love: ❤️");
344 /// let v: Vec<char> = s.chars().collect();
345 ///
346 /// assert_eq!(12, std::mem::size_of_val(&s[..]));
347 /// assert_eq!(32, std::mem::size_of_val(&v[..]));
348 /// ```
349 #[stable(feature = "rust1", since = "1.0.0")]
350 mod prim_char {}
351
352 #[doc(primitive = "unit")]
353 #[doc(alias = "(")]
354 #[doc(alias = ")")]
355 #[doc(alias = "()")]
356 //
357 /// The `()` type, also called "unit".
358 ///
359 /// The `()` type has exactly one value `()`, and is used when there
360 /// is no other meaningful value that could be returned. `()` is most
361 /// commonly seen implicitly: functions without a `-> ...` implicitly
362 /// have return type `()`, that is, these are equivalent:
363 ///
364 /// ```rust
365 /// fn long() -> () {}
366 ///
367 /// fn short() {}
368 /// ```
369 ///
370 /// The semicolon `;` can be used to discard the result of an
371 /// expression at the end of a block, making the expression (and thus
372 /// the block) evaluate to `()`. For example,
373 ///
374 /// ```rust
375 /// fn returns_i64() -> i64 {
376 ///     1i64
377 /// }
378 /// fn returns_unit() {
379 ///     1i64;
380 /// }
381 ///
382 /// let is_i64 = {
383 ///     returns_i64()
384 /// };
385 /// let is_unit = {
386 ///     returns_i64();
387 /// };
388 /// ```
389 ///
390 #[stable(feature = "rust1", since = "1.0.0")]
391 mod prim_unit {}
392
393 #[doc(primitive = "pointer")]
394 #[doc(alias = "ptr")]
395 #[doc(alias = "*")]
396 #[doc(alias = "*const")]
397 #[doc(alias = "*mut")]
398 //
399 /// Raw, unsafe pointers, `*const T`, and `*mut T`.
400 ///
401 /// *[See also the `std::ptr` module](ptr).*
402 ///
403 /// Working with raw pointers in Rust is uncommon, typically limited to a few patterns.
404 /// Raw pointers can be unaligned or [`null`]. However, when a raw pointer is
405 /// dereferenced (using the `*` operator), it must be non-null and aligned.
406 ///
407 /// Storing through a raw pointer using `*ptr = data` calls `drop` on the old value, so
408 /// [`write`] must be used if the type has drop glue and memory is not already
409 /// initialized - otherwise `drop` would be called on the uninitialized memory.
410 ///
411 /// Use the [`null`] and [`null_mut`] functions to create null pointers, and the
412 /// [`is_null`] method of the `*const T` and `*mut T` types to check for null.
413 /// The `*const T` and `*mut T` types also define the [`offset`] method, for
414 /// pointer math.
415 ///
416 /// # Common ways to create raw pointers
417 ///
418 /// ## 1. Coerce a reference (`&T`) or mutable reference (`&mut T`).
419 ///
420 /// ```
421 /// let my_num: i32 = 10;
422 /// let my_num_ptr: *const i32 = &my_num;
423 /// let mut my_speed: i32 = 88;
424 /// let my_speed_ptr: *mut i32 = &mut my_speed;
425 /// ```
426 ///
427 /// To get a pointer to a boxed value, dereference the box:
428 ///
429 /// ```
430 /// let my_num: Box<i32> = Box::new(10);
431 /// let my_num_ptr: *const i32 = &*my_num;
432 /// let mut my_speed: Box<i32> = Box::new(88);
433 /// let my_speed_ptr: *mut i32 = &mut *my_speed;
434 /// ```
435 ///
436 /// This does not take ownership of the original allocation
437 /// and requires no resource management later,
438 /// but you must not use the pointer after its lifetime.
439 ///
440 /// ## 2. Consume a box (`Box<T>`).
441 ///
442 /// The [`into_raw`] function consumes a box and returns
443 /// the raw pointer. It doesn't destroy `T` or deallocate any memory.
444 ///
445 /// ```
446 /// let my_speed: Box<i32> = Box::new(88);
447 /// let my_speed: *mut i32 = Box::into_raw(my_speed);
448 ///
449 /// // By taking ownership of the original `Box<T>` though
450 /// // we are obligated to put it together later to be destroyed.
451 /// unsafe {
452 ///     drop(Box::from_raw(my_speed));
453 /// }
454 /// ```
455 ///
456 /// Note that here the call to [`drop`] is for clarity - it indicates
457 /// that we are done with the given value and it should be destroyed.
458 ///
459 /// ## 3. Create it using `ptr::addr_of!`
460 ///
461 /// Instead of coercing a reference to a raw pointer, you can use the macros
462 /// [`ptr::addr_of!`] (for `*const T`) and [`ptr::addr_of_mut!`] (for `*mut T`).
463 /// These macros allow you to create raw pointers to fields to which you cannot
464 /// create a reference (without causing undefined behaviour), such as an
465 /// unaligned field. This might be necessary if packed structs or uninitialized
466 /// memory is involved.
467 ///
468 /// ```
469 /// #[derive(Debug, Default, Copy, Clone)]
470 /// #[repr(C, packed)]
471 /// struct S {
472 ///     aligned: u8,
473 ///     unaligned: u32,
474 /// }
475 /// let s = S::default();
476 /// let p = std::ptr::addr_of!(s.unaligned); // not allowed with coercion
477 /// ```
478 ///
479 /// ## 4. Get it from C.
480 ///
481 /// ```
482 /// # #![feature(rustc_private)]
483 /// extern crate libc;
484 ///
485 /// use std::mem;
486 ///
487 /// unsafe {
488 ///     let my_num: *mut i32 = libc::malloc(mem::size_of::<i32>()) as *mut i32;
489 ///     if my_num.is_null() {
490 ///         panic!("failed to allocate memory");
491 ///     }
492 ///     libc::free(my_num as *mut libc::c_void);
493 /// }
494 /// ```
495 ///
496 /// Usually you wouldn't literally use `malloc` and `free` from Rust,
497 /// but C APIs hand out a lot of pointers generally, so are a common source
498 /// of raw pointers in Rust.
499 ///
500 /// [`null`]: ptr::null
501 /// [`null_mut`]: ptr::null_mut
502 /// [`is_null`]: pointer::is_null
503 /// [`offset`]: pointer::offset
504 #[doc = concat!("[`into_raw`]: ", include_str!("../primitive_docs/box_into_raw.md"))]
505 /// [`drop`]: mem::drop
506 /// [`write`]: ptr::write
507 #[stable(feature = "rust1", since = "1.0.0")]
508 mod prim_pointer {}
509
510 #[doc(primitive = "array")]
511 #[doc(alias = "[]")]
512 #[doc(alias = "[T;N]")] // unfortunately, rustdoc doesn't have fuzzy search for aliases
513 #[doc(alias = "[T; N]")]
514 /// A fixed-size array, denoted `[T; N]`, for the element type, `T`, and the
515 /// non-negative compile-time constant size, `N`.
516 ///
517 /// There are two syntactic forms for creating an array:
518 ///
519 /// * A list with each element, i.e., `[x, y, z]`.
520 /// * A repeat expression `[x; N]`, which produces an array with `N` copies of `x`.
521 ///   The type of `x` must be [`Copy`].
522 ///
523 /// Note that `[expr; 0]` is allowed, and produces an empty array.
524 /// This will still evaluate `expr`, however, and immediately drop the resulting value, so
525 /// be mindful of side effects.
526 ///
527 /// Arrays of *any* size implement the following traits if the element type allows it:
528 ///
529 /// - [`Copy`]
530 /// - [`Clone`]
531 /// - [`Debug`]
532 /// - [`IntoIterator`] (implemented for `[T; N]`, `&[T; N]` and `&mut [T; N]`)
533 /// - [`PartialEq`], [`PartialOrd`], [`Eq`], [`Ord`]
534 /// - [`Hash`]
535 /// - [`AsRef`], [`AsMut`]
536 /// - [`Borrow`], [`BorrowMut`]
537 ///
538 /// Arrays of sizes from 0 to 32 (inclusive) implement the [`Default`] trait
539 /// if the element type allows it. As a stopgap, trait implementations are
540 /// statically generated up to size 32.
541 ///
542 /// Arrays coerce to [slices (`[T]`)][slice], so a slice method may be called on
543 /// an array. Indeed, this provides most of the API for working with arrays.
544 /// Slices have a dynamic size and do not coerce to arrays.
545 ///
546 /// You can move elements out of an array with a [slice pattern]. If you want
547 /// one element, see [`mem::replace`].
548 ///
549 /// # Examples
550 ///
551 /// ```
552 /// let mut array: [i32; 3] = [0; 3];
553 ///
554 /// array[1] = 1;
555 /// array[2] = 2;
556 ///
557 /// assert_eq!([1, 2], &array[1..]);
558 ///
559 /// // This loop prints: 0 1 2
560 /// for x in array {
561 ///     print!("{} ", x);
562 /// }
563 /// ```
564 ///
565 /// You can also iterate over reference to the array's elements:
566 ///
567 /// ```
568 /// let array: [i32; 3] = [0; 3];
569 ///
570 /// for x in &array { }
571 /// ```
572 ///
573 /// You can use a [slice pattern] to move elements out of an array:
574 ///
575 /// ```
576 /// fn move_away(_: String) { /* Do interesting things. */ }
577 ///
578 /// let [john, roa] = ["John".to_string(), "Roa".to_string()];
579 /// move_away(john);
580 /// move_away(roa);
581 /// ```
582 ///
583 /// # Editions
584 ///
585 /// Prior to Rust 1.53, arrays did not implement [`IntoIterator`] by value, so the method call
586 /// `array.into_iter()` auto-referenced into a [slice iterator](slice::iter). Right now, the old
587 /// behavior is preserved in the 2015 and 2018 editions of Rust for compatibility, ignoring
588 /// [`IntoIterator`] by value. In the future, the behavior on the 2015 and 2018 edition
589 /// might be made consistent to the behavior of later editions.
590 ///
591 /// ```rust,edition2018
592 /// // Rust 2015 and 2018:
593 ///
594 /// # #![allow(array_into_iter)] // override our `deny(warnings)`
595 /// let array: [i32; 3] = [0; 3];
596 ///
597 /// // This creates a slice iterator, producing references to each value.
598 /// for item in array.into_iter().enumerate() {
599 ///     let (i, x): (usize, &i32) = item;
600 ///     println!("array[{}] = {}", i, x);
601 /// }
602 ///
603 /// // The `array_into_iter` lint suggests this change for future compatibility:
604 /// for item in array.iter().enumerate() {
605 ///     let (i, x): (usize, &i32) = item;
606 ///     println!("array[{}] = {}", i, x);
607 /// }
608 ///
609 /// // You can explicitly iterate an array by value using
610 /// // `IntoIterator::into_iter` or `std::array::IntoIter::new`:
611 /// for item in IntoIterator::into_iter(array).enumerate() {
612 ///     let (i, x): (usize, i32) = item;
613 ///     println!("array[{}] = {}", i, x);
614 /// }
615 /// ```
616 ///
617 /// Starting in the 2021 edition, `array.into_iter()` uses `IntoIterator` normally to iterate
618 /// by value, and `iter()` should be used to iterate by reference like previous editions.
619 ///
620 /// ```rust,edition2021
621 /// // Rust 2021:
622 ///
623 /// let array: [i32; 3] = [0; 3];
624 ///
625 /// // This iterates by reference:
626 /// for item in array.iter().enumerate() {
627 ///     let (i, x): (usize, &i32) = item;
628 ///     println!("array[{}] = {}", i, x);
629 /// }
630 ///
631 /// // This iterates by value:
632 /// for item in array.into_iter().enumerate() {
633 ///     let (i, x): (usize, i32) = item;
634 ///     println!("array[{}] = {}", i, x);
635 /// }
636 /// ```
637 ///
638 /// Future language versions might start treating the `array.into_iter()`
639 /// syntax on editions 2015 and 2018 the same as on edition 2021. So code using
640 /// those older editions should still be written with this change in mind, to
641 /// prevent breakage in the future. The safest way to accomplish this is to
642 /// avoid the `into_iter` syntax on those editions. If an edition update is not
643 /// viable/desired, there are multiple alternatives:
644 /// * use `iter`, equivalent to the old behavior, creating references
645 /// * use [`IntoIterator::into_iter`], equivalent to the post-2021 behavior (Rust 1.53+)
646 /// * replace `for ... in array.into_iter() {` with `for ... in array {`,
647 ///   equivalent to the post-2021 behavior (Rust 1.53+)
648 ///
649 /// ```rust,edition2018
650 /// // Rust 2015 and 2018:
651 ///
652 /// let array: [i32; 3] = [0; 3];
653 ///
654 /// // This iterates by reference:
655 /// for item in array.iter() {
656 ///     let x: &i32 = item;
657 ///     println!("{}", x);
658 /// }
659 ///
660 /// // This iterates by value:
661 /// for item in IntoIterator::into_iter(array) {
662 ///     let x: i32 = item;
663 ///     println!("{}", x);
664 /// }
665 ///
666 /// // This iterates by value:
667 /// for item in array {
668 ///     let x: i32 = item;
669 ///     println!("{}", x);
670 /// }
671 ///
672 /// // IntoIter can also start a chain.
673 /// // This iterates by value:
674 /// for item in IntoIterator::into_iter(array).enumerate() {
675 ///     let (i, x): (usize, i32) = item;
676 ///     println!("array[{}] = {}", i, x);
677 /// }
678 /// ```
679 ///
680 /// [slice]: prim@slice
681 /// [`Debug`]: fmt::Debug
682 /// [`Hash`]: hash::Hash
683 /// [`Borrow`]: borrow::Borrow
684 /// [`BorrowMut`]: borrow::BorrowMut
685 /// [slice pattern]: ../reference/patterns.html#slice-patterns
686 #[stable(feature = "rust1", since = "1.0.0")]
687 mod prim_array {}
688
689 #[doc(primitive = "slice")]
690 #[doc(alias = "[")]
691 #[doc(alias = "]")]
692 #[doc(alias = "[]")]
693 /// A dynamically-sized view into a contiguous sequence, `[T]`. Contiguous here
694 /// means that elements are laid out so that every element is the same
695 /// distance from its neighbors.
696 ///
697 /// *[See also the `std::slice` module](crate::slice).*
698 ///
699 /// Slices are a view into a block of memory represented as a pointer and a
700 /// length.
701 ///
702 /// ```
703 /// // slicing a Vec
704 /// let vec = vec![1, 2, 3];
705 /// let int_slice = &vec[..];
706 /// // coercing an array to a slice
707 /// let str_slice: &[&str] = &["one", "two", "three"];
708 /// ```
709 ///
710 /// Slices are either mutable or shared. The shared slice type is `&[T]`,
711 /// while the mutable slice type is `&mut [T]`, where `T` represents the element
712 /// type. For example, you can mutate the block of memory that a mutable slice
713 /// points to:
714 ///
715 /// ```
716 /// let mut x = [1, 2, 3];
717 /// let x = &mut x[..]; // Take a full slice of `x`.
718 /// x[1] = 7;
719 /// assert_eq!(x, &[1, 7, 3]);
720 /// ```
721 ///
722 /// As slices store the length of the sequence they refer to, they have twice
723 /// the size of pointers to [`Sized`](marker/trait.Sized.html) types.
724 /// Also see the reference on
725 /// [dynamically sized types](../reference/dynamically-sized-types.html).
726 ///
727 /// ```
728 /// # use std::rc::Rc;
729 /// let pointer_size = std::mem::size_of::<&u8>();
730 /// assert_eq!(2 * pointer_size, std::mem::size_of::<&[u8]>());
731 /// assert_eq!(2 * pointer_size, std::mem::size_of::<*const [u8]>());
732 /// assert_eq!(2 * pointer_size, std::mem::size_of::<Box<[u8]>>());
733 /// assert_eq!(2 * pointer_size, std::mem::size_of::<Rc<[u8]>>());
734 /// ```
735 #[stable(feature = "rust1", since = "1.0.0")]
736 mod prim_slice {}
737
738 #[doc(primitive = "str")]
739 //
740 /// String slices.
741 ///
742 /// *[See also the `std::str` module](crate::str).*
743 ///
744 /// The `str` type, also called a 'string slice', is the most primitive string
745 /// type. It is usually seen in its borrowed form, `&str`. It is also the type
746 /// of string literals, `&'static str`.
747 ///
748 /// String slices are always valid UTF-8.
749 ///
750 /// # Examples
751 ///
752 /// String literals are string slices:
753 ///
754 /// ```
755 /// let hello = "Hello, world!";
756 ///
757 /// // with an explicit type annotation
758 /// let hello: &'static str = "Hello, world!";
759 /// ```
760 ///
761 /// They are `'static` because they're stored directly in the final binary, and
762 /// so will be valid for the `'static` duration.
763 ///
764 /// # Representation
765 ///
766 /// A `&str` is made up of two components: a pointer to some bytes, and a
767 /// length. You can look at these with the [`as_ptr`] and [`len`] methods:
768 ///
769 /// ```
770 /// use std::slice;
771 /// use std::str;
772 ///
773 /// let story = "Once upon a time...";
774 ///
775 /// let ptr = story.as_ptr();
776 /// let len = story.len();
777 ///
778 /// // story has nineteen bytes
779 /// assert_eq!(19, len);
780 ///
781 /// // We can re-build a str out of ptr and len. This is all unsafe because
782 /// // we are responsible for making sure the two components are valid:
783 /// let s = unsafe {
784 ///     // First, we build a &[u8]...
785 ///     let slice = slice::from_raw_parts(ptr, len);
786 ///
787 ///     // ... and then convert that slice into a string slice
788 ///     str::from_utf8(slice)
789 /// };
790 ///
791 /// assert_eq!(s, Ok(story));
792 /// ```
793 ///
794 /// [`as_ptr`]: str::as_ptr
795 /// [`len`]: str::len
796 ///
797 /// Note: This example shows the internals of `&str`. `unsafe` should not be
798 /// used to get a string slice under normal circumstances. Use `as_str`
799 /// instead.
800 #[stable(feature = "rust1", since = "1.0.0")]
801 mod prim_str {}
802
803 #[doc(primitive = "tuple")]
804 #[doc(alias = "(")]
805 #[doc(alias = ")")]
806 #[doc(alias = "()")]
807 //
808 /// A finite heterogeneous sequence, `(T, U, ..)`.
809 ///
810 /// Let's cover each of those in turn:
811 ///
812 /// Tuples are *finite*. In other words, a tuple has a length. Here's a tuple
813 /// of length `3`:
814 ///
815 /// ```
816 /// ("hello", 5, 'c');
817 /// ```
818 ///
819 /// 'Length' is also sometimes called 'arity' here; each tuple of a different
820 /// length is a different, distinct type.
821 ///
822 /// Tuples are *heterogeneous*. This means that each element of the tuple can
823 /// have a different type. In that tuple above, it has the type:
824 ///
825 /// ```
826 /// # let _:
827 /// (&'static str, i32, char)
828 /// # = ("hello", 5, 'c');
829 /// ```
830 ///
831 /// Tuples are a *sequence*. This means that they can be accessed by position;
832 /// this is called 'tuple indexing', and it looks like this:
833 ///
834 /// ```rust
835 /// let tuple = ("hello", 5, 'c');
836 ///
837 /// assert_eq!(tuple.0, "hello");
838 /// assert_eq!(tuple.1, 5);
839 /// assert_eq!(tuple.2, 'c');
840 /// ```
841 ///
842 /// The sequential nature of the tuple applies to its implementations of various
843 /// traits. For example, in [`PartialOrd`] and [`Ord`], the elements are compared
844 /// sequentially until the first non-equal set is found.
845 ///
846 /// For more about tuples, see [the book](../book/ch03-02-data-types.html#the-tuple-type).
847 ///
848 /// # Trait implementations
849 ///
850 /// If every type inside a tuple implements one of the following traits, then a
851 /// tuple itself also implements it.
852 ///
853 /// * [`Clone`]
854 /// * [`Copy`]
855 /// * [`PartialEq`]
856 /// * [`Eq`]
857 /// * [`PartialOrd`]
858 /// * [`Ord`]
859 /// * [`Debug`]
860 /// * [`Default`]
861 /// * [`Hash`]
862 ///
863 /// [`Debug`]: fmt::Debug
864 /// [`Hash`]: hash::Hash
865 ///
866 /// Due to a temporary restriction in Rust's type system, these traits are only
867 /// implemented on tuples of arity 12 or less. In the future, this may change.
868 ///
869 /// # Examples
870 ///
871 /// Basic usage:
872 ///
873 /// ```
874 /// let tuple = ("hello", 5, 'c');
875 ///
876 /// assert_eq!(tuple.0, "hello");
877 /// ```
878 ///
879 /// Tuples are often used as a return type when you want to return more than
880 /// one value:
881 ///
882 /// ```
883 /// fn calculate_point() -> (i32, i32) {
884 ///     // Don't do a calculation, that's not the point of the example
885 ///     (4, 5)
886 /// }
887 ///
888 /// let point = calculate_point();
889 ///
890 /// assert_eq!(point.0, 4);
891 /// assert_eq!(point.1, 5);
892 ///
893 /// // Combining this with patterns can be nicer.
894 ///
895 /// let (x, y) = calculate_point();
896 ///
897 /// assert_eq!(x, 4);
898 /// assert_eq!(y, 5);
899 /// ```
900 ///
901 #[stable(feature = "rust1", since = "1.0.0")]
902 mod prim_tuple {}
903
904 #[doc(primitive = "f32")]
905 /// A 32-bit floating point type (specifically, the "binary32" type defined in IEEE 754-2008).
906 ///
907 /// This type can represent a wide range of decimal numbers, like `3.5`, `27`,
908 /// `-113.75`, `0.0078125`, `34359738368`, `0`, `-1`. So unlike integer types
909 /// (such as `i32`), floating point types can represent non-integer numbers,
910 /// too.
911 ///
912 /// However, being able to represent this wide range of numbers comes at the
913 /// cost of precision: floats can only represent some of the real numbers and
914 /// calculation with floats round to a nearby representable number. For example,
915 /// `5.0` and `1.0` can be exactly represented as `f32`, but `1.0 / 5.0` results
916 /// in `0.20000000298023223876953125` since `0.2` cannot be exactly represented
917 /// as `f32`. Note, however, that printing floats with `println` and friends will
918 /// often discard insignificant digits: `println!("{}", 1.0f32 / 5.0f32)` will
919 /// print `0.2`.
920 ///
921 /// Additionally, `f32` can represent some special values:
922 ///
923 /// - −0.0: IEEE 754 floating point numbers have a bit that indicates their sign, so −0.0 is a
924 ///   possible value. For comparison −0.0 = +0.0, but floating point operations can carry
925 ///   the sign bit through arithmetic operations. This means −0.0 × +0.0 produces −0.0 and
926 ///   a negative number rounded to a value smaller than a float can represent also produces −0.0.
927 /// - [∞](#associatedconstant.INFINITY) and
928 ///   [−∞](#associatedconstant.NEG_INFINITY): these result from calculations
929 ///   like `1.0 / 0.0`.
930 /// - [NaN (not a number)](#associatedconstant.NAN): this value results from
931 ///   calculations like `(-1.0).sqrt()`. NaN has some potentially unexpected
932 ///   behavior: it is unequal to any float, including itself! It is also neither
933 ///   smaller nor greater than any float, making it impossible to sort. Lastly,
934 ///   it is considered infectious as almost all calculations where one of the
935 ///   operands is NaN will also result in NaN.
936 ///
937 /// For more information on floating point numbers, see [Wikipedia][wikipedia].
938 ///
939 /// *[See also the `std::f32::consts` module](crate::f32::consts).*
940 ///
941 /// [wikipedia]: https://en.wikipedia.org/wiki/Single-precision_floating-point_format
942 #[stable(feature = "rust1", since = "1.0.0")]
943 mod prim_f32 {}
944
945 #[doc(primitive = "f64")]
946 /// A 64-bit floating point type (specifically, the "binary64" type defined in IEEE 754-2008).
947 ///
948 /// This type is very similar to [`f32`], but has increased
949 /// precision by using twice as many bits. Please see [the documentation for
950 /// `f32`][`f32`] or [Wikipedia on double precision
951 /// values][wikipedia] for more information.
952 ///
953 /// *[See also the `std::f64::consts` module](crate::f64::consts).*
954 ///
955 /// [`f32`]: prim@f32
956 /// [wikipedia]: https://en.wikipedia.org/wiki/Double-precision_floating-point_format
957 #[stable(feature = "rust1", since = "1.0.0")]
958 mod prim_f64 {}
959
960 #[doc(primitive = "i8")]
961 //
962 /// The 8-bit signed integer type.
963 #[stable(feature = "rust1", since = "1.0.0")]
964 mod prim_i8 {}
965
966 #[doc(primitive = "i16")]
967 //
968 /// The 16-bit signed integer type.
969 #[stable(feature = "rust1", since = "1.0.0")]
970 mod prim_i16 {}
971
972 #[doc(primitive = "i32")]
973 //
974 /// The 32-bit signed integer type.
975 #[stable(feature = "rust1", since = "1.0.0")]
976 mod prim_i32 {}
977
978 #[doc(primitive = "i64")]
979 //
980 /// The 64-bit signed integer type.
981 #[stable(feature = "rust1", since = "1.0.0")]
982 mod prim_i64 {}
983
984 #[doc(primitive = "i128")]
985 //
986 /// The 128-bit signed integer type.
987 #[stable(feature = "i128", since = "1.26.0")]
988 mod prim_i128 {}
989
990 #[doc(primitive = "u8")]
991 //
992 /// The 8-bit unsigned integer type.
993 #[stable(feature = "rust1", since = "1.0.0")]
994 mod prim_u8 {}
995
996 #[doc(primitive = "u16")]
997 //
998 /// The 16-bit unsigned integer type.
999 #[stable(feature = "rust1", since = "1.0.0")]
1000 mod prim_u16 {}
1001
1002 #[doc(primitive = "u32")]
1003 //
1004 /// The 32-bit unsigned integer type.
1005 #[stable(feature = "rust1", since = "1.0.0")]
1006 mod prim_u32 {}
1007
1008 #[doc(primitive = "u64")]
1009 //
1010 /// The 64-bit unsigned integer type.
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 mod prim_u64 {}
1013
1014 #[doc(primitive = "u128")]
1015 //
1016 /// The 128-bit unsigned integer type.
1017 #[stable(feature = "i128", since = "1.26.0")]
1018 mod prim_u128 {}
1019
1020 #[doc(primitive = "isize")]
1021 //
1022 /// The pointer-sized signed integer type.
1023 ///
1024 /// The size of this primitive is how many bytes it takes to reference any
1025 /// location in memory. For example, on a 32 bit target, this is 4 bytes
1026 /// and on a 64 bit target, this is 8 bytes.
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 mod prim_isize {}
1029
1030 #[doc(primitive = "usize")]
1031 //
1032 /// The pointer-sized unsigned integer type.
1033 ///
1034 /// The size of this primitive is how many bytes it takes to reference any
1035 /// location in memory. For example, on a 32 bit target, this is 4 bytes
1036 /// and on a 64 bit target, this is 8 bytes.
1037 #[stable(feature = "rust1", since = "1.0.0")]
1038 mod prim_usize {}
1039
1040 #[doc(primitive = "reference")]
1041 #[doc(alias = "&")]
1042 #[doc(alias = "&mut")]
1043 //
1044 /// References, both shared and mutable.
1045 ///
1046 /// A reference represents a borrow of some owned value. You can get one by using the `&` or `&mut`
1047 /// operators on a value, or by using a [`ref`](../std/keyword.ref.html) or
1048 /// <code>[ref](../std/keyword.ref.html) [mut](../std/keyword.mut.html)</code> pattern.
1049 ///
1050 /// For those familiar with pointers, a reference is just a pointer that is assumed to be
1051 /// aligned, not null, and pointing to memory containing a valid value of `T` - for example,
1052 /// <code>&[bool]</code> can only point to an allocation containing the integer values `1`
1053 /// ([`true`](../std/keyword.true.html)) or `0` ([`false`](../std/keyword.false.html)), but
1054 /// creating a <code>&[bool]</code> that points to an allocation containing
1055 /// the value `3` causes undefined behaviour.
1056 /// In fact, <code>[Option]\<&T></code> has the same memory representation as a
1057 /// nullable but aligned pointer, and can be passed across FFI boundaries as such.
1058 ///
1059 /// In most cases, references can be used much like the original value. Field access, method
1060 /// calling, and indexing work the same (save for mutability rules, of course). In addition, the
1061 /// comparison operators transparently defer to the referent's implementation, allowing references
1062 /// to be compared the same as owned values.
1063 ///
1064 /// References have a lifetime attached to them, which represents the scope for which the borrow is
1065 /// valid. A lifetime is said to "outlive" another one if its representative scope is as long or
1066 /// longer than the other. The `'static` lifetime is the longest lifetime, which represents the
1067 /// total life of the program. For example, string literals have a `'static` lifetime because the
1068 /// text data is embedded into the binary of the program, rather than in an allocation that needs
1069 /// to be dynamically managed.
1070 ///
1071 /// `&mut T` references can be freely coerced into `&T` references with the same referent type, and
1072 /// references with longer lifetimes can be freely coerced into references with shorter ones.
1073 ///
1074 /// Reference equality by address, instead of comparing the values pointed to, is accomplished via
1075 /// implicit reference-pointer coercion and raw pointer equality via [`ptr::eq`], while
1076 /// [`PartialEq`] compares values.
1077 ///
1078 /// ```
1079 /// use std::ptr;
1080 ///
1081 /// let five = 5;
1082 /// let other_five = 5;
1083 /// let five_ref = &five;
1084 /// let same_five_ref = &five;
1085 /// let other_five_ref = &other_five;
1086 ///
1087 /// assert!(five_ref == same_five_ref);
1088 /// assert!(five_ref == other_five_ref);
1089 ///
1090 /// assert!(ptr::eq(five_ref, same_five_ref));
1091 /// assert!(!ptr::eq(five_ref, other_five_ref));
1092 /// ```
1093 ///
1094 /// For more information on how to use references, see [the book's section on "References and
1095 /// Borrowing"][book-refs].
1096 ///
1097 /// [book-refs]: ../book/ch04-02-references-and-borrowing.html
1098 ///
1099 /// # Trait implementations
1100 ///
1101 /// The following traits are implemented for all `&T`, regardless of the type of its referent:
1102 ///
1103 /// * [`Copy`]
1104 /// * [`Clone`] \(Note that this will not defer to `T`'s `Clone` implementation if it exists!)
1105 /// * [`Deref`]
1106 /// * [`Borrow`]
1107 /// * [`fmt::Pointer`]
1108 ///
1109 /// [`Deref`]: ops::Deref
1110 /// [`Borrow`]: borrow::Borrow
1111 ///
1112 /// `&mut T` references get all of the above except `Copy` and `Clone` (to prevent creating
1113 /// multiple simultaneous mutable borrows), plus the following, regardless of the type of its
1114 /// referent:
1115 ///
1116 /// * [`DerefMut`]
1117 /// * [`BorrowMut`]
1118 ///
1119 /// [`DerefMut`]: ops::DerefMut
1120 /// [`BorrowMut`]: borrow::BorrowMut
1121 /// [bool]: prim@bool
1122 ///
1123 /// The following traits are implemented on `&T` references if the underlying `T` also implements
1124 /// that trait:
1125 ///
1126 /// * All the traits in [`std::fmt`] except [`fmt::Pointer`] (which is implemented regardless of the type of its referent) and [`fmt::Write`]
1127 /// * [`PartialOrd`]
1128 /// * [`Ord`]
1129 /// * [`PartialEq`]
1130 /// * [`Eq`]
1131 /// * [`AsRef`]
1132 /// * [`Fn`] \(in addition, `&T` references get [`FnMut`] and [`FnOnce`] if `T: Fn`)
1133 /// * [`Hash`]
1134 /// * [`ToSocketAddrs`]
1135 /// * [`Send`] \(`&T` references also require <code>T: [Sync]</code>)
1136 ///
1137 /// [`std::fmt`]: fmt
1138 /// [`Hash`]: hash::Hash
1139 #[doc = concat!("[`ToSocketAddrs`]: ", include_str!("../primitive_docs/net_tosocketaddrs.md"))]
1140 ///
1141 /// `&mut T` references get all of the above except `ToSocketAddrs`, plus the following, if `T`
1142 /// implements that trait:
1143 ///
1144 /// * [`AsMut`]
1145 /// * [`FnMut`] \(in addition, `&mut T` references get [`FnOnce`] if `T: FnMut`)
1146 /// * [`fmt::Write`]
1147 /// * [`Iterator`]
1148 /// * [`DoubleEndedIterator`]
1149 /// * [`ExactSizeIterator`]
1150 /// * [`FusedIterator`]
1151 /// * [`TrustedLen`]
1152 /// * [`io::Write`]
1153 /// * [`Read`]
1154 /// * [`Seek`]
1155 /// * [`BufRead`]
1156 ///
1157 /// [`FusedIterator`]: iter::FusedIterator
1158 /// [`TrustedLen`]: iter::TrustedLen
1159 #[doc = concat!("[`Seek`]: ", include_str!("../primitive_docs/io_seek.md"))]
1160 #[doc = concat!("[`BufRead`]: ", include_str!("../primitive_docs/io_bufread.md"))]
1161 #[doc = concat!("[`Read`]: ", include_str!("../primitive_docs/io_read.md"))]
1162 #[doc = concat!("[`io::Write`]: ", include_str!("../primitive_docs/io_write.md"))]
1163 ///
1164 /// Note that due to method call deref coercion, simply calling a trait method will act like they
1165 /// work on references as well as they do on owned values! The implementations described here are
1166 /// meant for generic contexts, where the final type `T` is a type parameter or otherwise not
1167 /// locally known.
1168 #[stable(feature = "rust1", since = "1.0.0")]
1169 mod prim_ref {}
1170
1171 #[doc(primitive = "fn")]
1172 //
1173 /// Function pointers, like `fn(usize) -> bool`.
1174 ///
1175 /// *See also the traits [`Fn`], [`FnMut`], and [`FnOnce`].*
1176 ///
1177 /// [`Fn`]: ops::Fn
1178 /// [`FnMut`]: ops::FnMut
1179 /// [`FnOnce`]: ops::FnOnce
1180 ///
1181 /// Function pointers are pointers that point to *code*, not data. They can be called
1182 /// just like functions. Like references, function pointers are, among other things, assumed to
1183 /// not be null, so if you want to pass a function pointer over FFI and be able to accommodate null
1184 /// pointers, make your type [`Option<fn()>`](core::option#options-and-pointers-nullable-pointers)
1185 /// with your required signature.
1186 ///
1187 /// ### Safety
1188 ///
1189 /// Plain function pointers are obtained by casting either plain functions, or closures that don't
1190 /// capture an environment:
1191 ///
1192 /// ```
1193 /// fn add_one(x: usize) -> usize {
1194 ///     x + 1
1195 /// }
1196 ///
1197 /// let ptr: fn(usize) -> usize = add_one;
1198 /// assert_eq!(ptr(5), 6);
1199 ///
1200 /// let clos: fn(usize) -> usize = |x| x + 5;
1201 /// assert_eq!(clos(5), 10);
1202 /// ```
1203 ///
1204 /// In addition to varying based on their signature, function pointers come in two flavors: safe
1205 /// and unsafe. Plain `fn()` function pointers can only point to safe functions,
1206 /// while `unsafe fn()` function pointers can point to safe or unsafe functions.
1207 ///
1208 /// ```
1209 /// fn add_one(x: usize) -> usize {
1210 ///     x + 1
1211 /// }
1212 ///
1213 /// unsafe fn add_one_unsafely(x: usize) -> usize {
1214 ///     x + 1
1215 /// }
1216 ///
1217 /// let safe_ptr: fn(usize) -> usize = add_one;
1218 ///
1219 /// //ERROR: mismatched types: expected normal fn, found unsafe fn
1220 /// //let bad_ptr: fn(usize) -> usize = add_one_unsafely;
1221 ///
1222 /// let unsafe_ptr: unsafe fn(usize) -> usize = add_one_unsafely;
1223 /// let really_safe_ptr: unsafe fn(usize) -> usize = add_one;
1224 /// ```
1225 ///
1226 /// ### ABI
1227 ///
1228 /// On top of that, function pointers can vary based on what ABI they use. This
1229 /// is achieved by adding the `extern` keyword before the type, followed by the
1230 /// ABI in question. The default ABI is "Rust", i.e., `fn()` is the exact same
1231 /// type as `extern "Rust" fn()`. A pointer to a function with C ABI would have
1232 /// type `extern "C" fn()`.
1233 ///
1234 /// `extern "ABI" { ... }` blocks declare functions with ABI "ABI". The default
1235 /// here is "C", i.e., functions declared in an `extern {...}` block have "C"
1236 /// ABI.
1237 ///
1238 /// For more information and a list of supported ABIs, see [the nomicon's
1239 /// section on foreign calling conventions][nomicon-abi].
1240 ///
1241 /// [nomicon-abi]: ../nomicon/ffi.html#foreign-calling-conventions
1242 ///
1243 /// ### Variadic functions
1244 ///
1245 /// Extern function declarations with the "C" or "cdecl" ABIs can also be *variadic*, allowing them
1246 /// to be called with a variable number of arguments. Normal Rust functions, even those with an
1247 /// `extern "ABI"`, cannot be variadic. For more information, see [the nomicon's section on
1248 /// variadic functions][nomicon-variadic].
1249 ///
1250 /// [nomicon-variadic]: ../nomicon/ffi.html#variadic-functions
1251 ///
1252 /// ### Creating function pointers
1253 ///
1254 /// When `bar` is the name of a function, then the expression `bar` is *not* a
1255 /// function pointer. Rather, it denotes a value of an unnameable type that
1256 /// uniquely identifies the function `bar`. The value is zero-sized because the
1257 /// type already identifies the function. This has the advantage that "calling"
1258 /// the value (it implements the `Fn*` traits) does not require dynamic
1259 /// dispatch.
1260 ///
1261 /// This zero-sized type *coerces* to a regular function pointer. For example:
1262 ///
1263 /// ```rust
1264 /// use std::mem;
1265 ///
1266 /// fn bar(x: i32) {}
1267 ///
1268 /// let not_bar_ptr = bar; // `not_bar_ptr` is zero-sized, uniquely identifying `bar`
1269 /// assert_eq!(mem::size_of_val(&not_bar_ptr), 0);
1270 ///
1271 /// let bar_ptr: fn(i32) = not_bar_ptr; // force coercion to function pointer
1272 /// assert_eq!(mem::size_of_val(&bar_ptr), mem::size_of::<usize>());
1273 ///
1274 /// let footgun = &bar; // this is a shared reference to the zero-sized type identifying `bar`
1275 /// ```
1276 ///
1277 /// The last line shows that `&bar` is not a function pointer either. Rather, it
1278 /// is a reference to the function-specific ZST. `&bar` is basically never what you
1279 /// want when `bar` is a function.
1280 ///
1281 /// ### Traits
1282 ///
1283 /// Function pointers implement the following traits:
1284 ///
1285 /// * [`Clone`]
1286 /// * [`PartialEq`]
1287 /// * [`Eq`]
1288 /// * [`PartialOrd`]
1289 /// * [`Ord`]
1290 /// * [`Hash`]
1291 /// * [`Pointer`]
1292 /// * [`Debug`]
1293 ///
1294 /// [`Hash`]: hash::Hash
1295 /// [`Pointer`]: fmt::Pointer
1296 ///
1297 /// Due to a temporary restriction in Rust's type system, these traits are only implemented on
1298 /// functions that take 12 arguments or less, with the `"Rust"` and `"C"` ABIs. In the future, this
1299 /// may change.
1300 ///
1301 /// In addition, function pointers of *any* signature, ABI, or safety are [`Copy`], and all *safe*
1302 /// function pointers implement [`Fn`], [`FnMut`], and [`FnOnce`]. This works because these traits
1303 /// are specially known to the compiler.
1304 #[stable(feature = "rust1", since = "1.0.0")]
1305 mod prim_fn {}