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