primitive_docs.rs 42.3 KB
Newer Older
1
#[doc(primitive = "bool")]
G
Guillaume Gomez 已提交
2 3
#[doc(alias = "true")]
#[doc(alias = "false")]
4 5
/// The boolean type.
///
6 7
/// The `bool` represents a value, which could only be either `true` or `false`. If you cast
/// a `bool` into an integer, `true` will be 1 and `false` will be 0.
8 9 10 11 12 13
///
/// # Basic usage
///
/// `bool` implements various traits, such as [`BitAnd`], [`BitOr`], [`Not`], etc.,
/// which allow us to perform boolean operations using `&`, `|` and `!`.
///
C
Camelid 已提交
14
/// `if` requires a `bool` value as its conditional. [`assert!`], which is an
C
Camelid 已提交
15 16
/// important macro in testing, checks whether an expression is `true` and panics
/// if it isn't.
17 18 19 20 21 22
///
/// ```
/// let bool_val = true & false | false;
/// assert!(!bool_val);
/// ```
///
23 24 25
/// [`BitAnd`]: ops::BitAnd
/// [`BitOr`]: ops::BitOr
/// [`Not`]: ops::Not
26 27 28
///
/// # Examples
///
C
Camelid 已提交
29
/// A trivial example of the usage of `bool`:
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
///
/// ```
/// let praise_the_borrow_checker = true;
///
/// // using the `if` conditional
/// if praise_the_borrow_checker {
///     println!("oh, yeah!");
/// } else {
///     println!("what?!!");
/// }
///
/// // ... or, a match pattern
/// match praise_the_borrow_checker {
///     true => println!("keep praising!"),
///     false => println!("you should praise!"),
/// }
/// ```
///
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 52 53 54 55 56
///
/// Now an example of `bool` cast to integer type:
///
/// ```
/// assert_eq!(true as i32, 1);
/// assert_eq!(false as i32, 0);
/// ```
57
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
58
mod prim_bool {}
59

A
Andrew Cann 已提交
60
#[doc(primitive = "never")]
G
Guillaume Gomez 已提交
61
#[doc(alias = "!")]
A
Andrew Cann 已提交
62 63 64 65 66 67 68 69
//
/// The `!` type, also called "never".
///
/// `!` represents the type of computations which never resolve to any value at all. For example,
/// the [`exit`] function `fn exit(code: i32) -> !` exits the process without ever returning, and
/// so returns `!`.
///
/// `break`, `continue` and `return` expressions also have type `!`. For example we are allowed to
A
Andrew Cann 已提交
70
/// write:
A
Andrew Cann 已提交
71 72
///
/// ```
73
/// #![feature(never_type)]
A
Andrew Cann 已提交
74
/// # fn foo() -> u32 {
A
Andrew Cann 已提交
75
/// let x: ! = {
A
Andrew Cann 已提交
76
///     return 123
A
Andrew Cann 已提交
77
/// };
A
Andrew Cann 已提交
78
/// # }
A
Andrew Cann 已提交
79 80 81 82 83 84 85 86 87 88
/// ```
///
/// Although the `let` is pointless here, it illustrates the meaning of `!`. Since `x` is never
/// assigned a value (because `return` returns from the entire function), `x` can be given type
/// `!`. We could also replace `return 123` with a `panic!` or a never-ending `loop` and this code
/// would still be valid.
///
/// A more realistic usage of `!` is in this code:
///
/// ```
A
Andrew Cann 已提交
89 90
/// # fn get_a_number() -> Option<u32> { None }
/// # loop {
A
Andrew Cann 已提交
91 92 93
/// let num: u32 = match get_a_number() {
///     Some(num) => num,
///     None => break,
A
Andrew Cann 已提交
94 95
/// };
/// # }
A
Andrew Cann 已提交
96 97
/// ```
///
A
Andrew Cann 已提交
98 99
/// Both match arms must produce values of type [`u32`], but since `break` never produces a value
/// at all we know it can never produce a value which isn't a [`u32`]. This illustrates another
A
Andrew Cann 已提交
100 101
/// behaviour of the `!` type - expressions with type `!` will coerce into any other type.
///
102
/// [`u32`]: prim@u32
103
/// [`exit`]: process::exit
A
Andrew Cann 已提交
104 105 106
///
/// # `!` and generics
///
C
Clar Charr 已提交
107
/// ## Infallible errors
C
Clar Charr 已提交
108
///
A
Andrew Cann 已提交
109 110 111 112
/// The main place you'll see `!` used explicitly is in generic code. Consider the [`FromStr`]
/// trait:
///
/// ```
A
Andrew Cann 已提交
113 114 115
/// trait FromStr: Sized {
///     type Err;
///     fn from_str(s: &str) -> Result<Self, Self::Err>;
A
Andrew Cann 已提交
116 117 118
/// }
/// ```
///
A
Andrew Cann 已提交
119
/// When implementing this trait for [`String`] we need to pick a type for [`Err`]. And since
A
Andrew Cann 已提交
120
/// converting a string into a string will never result in an error, the appropriate type is `!`.
A
Andrew Cann 已提交
121
/// (Currently the type actually used is an enum with no variants, though this is only because `!`
F
Typo  
Felix Rabe 已提交
122
/// was added to Rust at a later date and it may change in the future.) With an [`Err`] type of
A
Andrew Cann 已提交
123 124
/// `!`, if we have to call [`String::from_str`] for some reason the result will be a
/// [`Result<String, !>`] which we can unpack like this:
A
Andrew Cann 已提交
125
///
C
Camelid 已提交
126 127 128
/// ```
/// #![feature(exhaustive_patterns)]
/// use std::str::FromStr;
A
Andrew Cann 已提交
129 130 131
/// let Ok(s) = String::from_str("hello");
/// ```
///
A
Andrew Cann 已提交
132 133 134 135
/// Since the [`Err`] variant contains a `!`, it can never occur. If the `exhaustive_patterns`
/// feature is present this means we can exhaustively match on [`Result<T, !>`] by just taking the
/// [`Ok`] variant. This illustrates another behaviour of `!` - it can be used to "delete" certain
/// enum variants from generic types like `Result`.
A
Andrew Cann 已提交
136
///
C
Clar Charr 已提交
137 138
/// ## Infinite loops
///
C
Clar Charr 已提交
139
/// While [`Result<T, !>`] is very useful for removing errors, `!` can also be used to remove
C
Clar Charr 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
/// successes as well. If we think of [`Result<T, !>`] as "if this function returns, it has not
/// errored," we get a very intuitive idea of [`Result<!, E>`] as well: if the function returns, it
/// *has* errored.
///
/// For example, consider the case of a simple web server, which can be simplified to:
///
/// ```ignore (hypothetical-example)
/// loop {
///     let (client, request) = get_request().expect("disconnected");
///     let response = request.process();
///     response.send(client);
/// }
/// ```
///
/// Currently, this isn't ideal, because we simply panic whenever we fail to get a new connection.
/// Instead, we'd like to keep track of this error, like this:
///
/// ```ignore (hypothetical-example)
/// loop {
///     match get_request() {
///         Err(err) => break err,
///         Ok((client, request)) => {
///             let response = request.process();
///             response.send(client);
///         },
///     }
/// }
/// ```
///
/// Now, when the server disconnects, we exit the loop with an error instead of panicking. While it
C
Clar Charr 已提交
170
/// might be intuitive to simply return the error, we might want to wrap it in a [`Result<!, E>`]
C
Clar Charr 已提交
171 172 173 174
/// instead:
///
/// ```ignore (hypothetical-example)
/// fn server_loop() -> Result<!, ConnectionError> {
C
Clar Charr 已提交
175
///     loop {
C
Clar Charr 已提交
176 177 178
///         let (client, request) = get_request()?;
///         let response = request.process();
///         response.send(client);
C
Clar Charr 已提交
179
///     }
C
Clar Charr 已提交
180 181 182 183
/// }
/// ```
///
/// Now, we can use `?` instead of `match`, and the return type makes a lot more sense: if the loop
C
Clar Charr 已提交
184 185
/// ever stops, it means that an error occurred. We don't even have to wrap the loop in an `Ok`
/// because `!` coerces to `Result<!, ConnectionError>` automatically.
C
Clar Charr 已提交
186
///
187 188 189
/// [`String::from_str`]: str::FromStr::from_str
/// [`String`]: string::String
/// [`FromStr`]: str::FromStr
A
Andrew Cann 已提交
190 191 192 193
///
/// # `!` and traits
///
/// When writing your own traits, `!` should have an `impl` whenever there is an obvious `impl`
194 195 196
/// which doesn't `panic!`. The reason is that functions returning an `impl Trait` where `!`
/// does not have an `impl` of `Trait` cannot diverge as their only possible code path. In other
/// words, they can't return `!` from every code path. As an example, this code doesn't compile:
C
Camelid 已提交
197 198
///
/// ```compile_fail
199
/// use std::ops::Add;
C
Camelid 已提交
200 201 202 203 204 205
///
/// fn foo() -> impl Add<u32> {
///     unimplemented!()
/// }
/// ```
///
206
/// But this code does:
C
Camelid 已提交
207 208
///
/// ```
209
/// use std::ops::Add;
C
Camelid 已提交
210 211 212 213 214 215 216 217 218 219
///
/// fn foo() -> impl Add<u32> {
///     if true {
///         unimplemented!()
///     } else {
///         0
///     }
/// }
/// ```
///
220
/// The reason is that, in the first example, there are many possible types that `!` could coerce
C
Camelid 已提交
221
/// to, because many types implement `Add<u32>`. However, in the second example,
C
Camelid 已提交
222
/// the `else` branch returns a `0`, which the compiler infers from the return type to be of type
C
Camelid 已提交
223 224
/// `u32`. Since `u32` is a concrete type, `!` can and will be coerced to it. See issue [#36375]
/// for more information on this quirk of `!`.
C
Camelid 已提交
225 226 227 228
///
/// [#36375]: https://github.com/rust-lang/rust/issues/36375
///
/// As it turns out, though, most traits can have an `impl` for `!`. Take [`Debug`]
A
Andrew Cann 已提交
229 230 231
/// for example:
///
/// ```
232
/// #![feature(never_type)]
233 234 235 236
/// # use std::fmt;
/// # trait Debug {
/// #     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result;
/// # }
A
Andrew Cann 已提交
237
/// impl Debug for ! {
238
///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
A
Andrew Cann 已提交
239 240 241 242 243
///         *self
///     }
/// }
/// ```
///
A
Andrew Cann 已提交
244 245 246 247
/// Once again we're using `!`'s ability to coerce into any other type, in this case
/// [`fmt::Result`]. Since this method takes a `&!` as an argument we know that it can never be
/// called (because there is no value of type `!` for it to be called with). Writing `*self`
/// essentially tells the compiler "We know that this code can never be run, so just treat the
G
gardrek 已提交
248
/// entire function body as having type [`fmt::Result`]". This pattern can be used a lot when
A
Andrew Cann 已提交
249
/// implementing traits for `!`. Generally, any trait which only has methods which take a `self`
G
gardrek 已提交
250
/// parameter should have such an impl.
A
Andrew Cann 已提交
251 252 253 254 255 256 257 258 259 260 261
///
/// On the other hand, one trait which would not be appropriate to implement is [`Default`]:
///
/// ```
/// trait Default {
///     fn default() -> Self;
/// }
/// ```
///
/// Since `!` has no values, it has no default value either. It's true that we could write an
/// `impl` for this which simply panics, but the same is true for any type (we could `impl
A
Andrew Cann 已提交
262
/// Default` for (eg.) [`File`] by just making [`default()`] panic.)
A
Andrew Cann 已提交
263
///
264 265 266
/// [`File`]: fs::File
/// [`Debug`]: fmt::Debug
/// [`default()`]: Default::default
A
Andrew Cann 已提交
267
///
268
#[unstable(feature = "never_type", issue = "35121")]
M
Mark Rousskov 已提交
269
mod prim_never {}
A
Andrew Cann 已提交
270

271 272
#[doc(primitive = "char")]
//
S
Steve Klabnik 已提交
273
/// A character type.
274
///
S
Steve Klabnik 已提交
275 276 277 278
/// The `char` type represents a single character. More specifically, since
/// 'character' isn't a well-defined concept in Unicode, `char` is a '[Unicode
/// scalar value]', which is similar to, but not the same as, a '[Unicode code
/// point]'.
279
///
S
Smitty 已提交
280 281
/// [Unicode scalar value]: https://www.unicode.org/glossary/#unicode_scalar_value
/// [Unicode code point]: https://www.unicode.org/glossary/#code_point
282
///
S
Steve Klabnik 已提交
283 284 285
/// This documentation describes a number of methods and trait implementations on the
/// `char` type. For technical reasons, there is additional, separate
/// documentation in [the `std::char` module](char/index.html) as well.
286
///
S
Steve Klabnik 已提交
287 288 289
/// # Representation
///
/// `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:
S
Steve Klabnik 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
///
/// ```
/// let v = vec!['h', 'e', 'l', 'l', 'o'];
///
/// // five elements times four bytes for each element
/// assert_eq!(20, v.len() * std::mem::size_of::<char>());
///
/// let s = String::from("hello");
///
/// // five elements times one byte per element
/// assert_eq!(5, s.len() * std::mem::size_of::<u8>());
/// ```
///
/// [`String`]: string/struct.String.html
///
306
/// As always, remember that a human intuition for 'character' might 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:
S
Steve Klabnik 已提交
309 310
///
/// ```
311 312 313 314 315 316 317 318 319 320 321
/// let mut chars = "é".chars();
/// // U+00e9: 'latin small letter e with acute'
/// assert_eq!(Some('\u{00e9}'), chars.next());
/// assert_eq!(None, chars.next());
///
/// let mut chars = "é".chars();
/// // U+0065: 'latin small letter e'
/// assert_eq!(Some('\u{0065}'), chars.next());
/// // U+0301: 'combining acute accent'
/// assert_eq!(Some('\u{0301}'), chars.next());
/// assert_eq!(None, chars.next());
S
Steve Klabnik 已提交
322 323
/// ```
///
324 325 326
/// This means that the contents of the first string above _will_ fit into a
/// `char` while the contents of the second string _will not_. Trying to create
/// a `char` literal with the contents of the second string gives an error:
S
Steve Klabnik 已提交
327 328
///
/// ```text
329 330
/// error: character literal may only contain one codepoint: 'é'
/// let c = 'é';
E
Esteban Küber 已提交
331
///         ^^^
S
Steve Klabnik 已提交
332 333
/// ```
///
334 335
/// Another implication of the 4-byte fixed size of a `char` is that
/// per-`char` processing can end up using a lot more memory:
S
Steve Klabnik 已提交
336 337 338 339 340
///
/// ```
/// let s = String::from("love: ❤️");
/// let v: Vec<char> = s.chars().collect();
///
P
Peter Hall 已提交
341 342
/// assert_eq!(12, std::mem::size_of_val(&s[..]));
/// assert_eq!(32, std::mem::size_of_val(&v[..]));
S
Steve Klabnik 已提交
343
/// ```
344
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
345
mod prim_char {}
346 347

#[doc(primitive = "unit")]
R
r00ster 已提交
348 349 350
#[doc(alias = "(")]
#[doc(alias = ")")]
#[doc(alias = "()")]
351
//
352
/// The `()` type, also called "unit".
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
///
/// The `()` type has exactly one value `()`, and is used when there
/// is no other meaningful value that could be returned. `()` is most
/// commonly seen implicitly: functions without a `-> ...` implicitly
/// have return type `()`, that is, these are equivalent:
///
/// ```rust
/// fn long() -> () {}
///
/// fn short() {}
/// ```
///
/// The semicolon `;` can be used to discard the result of an
/// expression at the end of a block, making the expression (and thus
/// the block) evaluate to `()`. For example,
///
/// ```rust
/// fn returns_i64() -> i64 {
///     1i64
/// }
/// fn returns_unit() {
///     1i64;
/// }
///
/// let is_i64 = {
///     returns_i64()
/// };
/// let is_unit = {
///     returns_i64();
/// };
/// ```
///
385
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
386
mod prim_unit {}
387

388
#[doc(alias = "ptr")]
389 390
#[doc(primitive = "pointer")]
//
B
Brian Anderson 已提交
391
/// Raw, unsafe pointers, `*const T`, and `*mut T`.
392
///
C
Camelid 已提交
393
/// *[See also the `std::ptr` module](ptr).*
M
Michael Lamparski 已提交
394
///
395
/// Working with raw pointers in Rust is uncommon, typically limited to a few patterns.
R
Ralf Jung 已提交
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.
R
Ralf Jung 已提交
398
///
R
Ralf Jung 已提交
399
/// Storing through a raw pointer using `*ptr = data` calls `drop` on the old value, so
R
Ralf Jung 已提交
400
/// [`write`] must be used if the type has drop glue and memory is not already
R
Ralf Jung 已提交
401
/// initialized - otherwise `drop` would be called on the uninitialized memory.
402
///
403 404 405 406
/// Use the [`null`] and [`null_mut`] functions to create null pointers, and the
/// [`is_null`] method of the `*const T` and `*mut T` types to check for null.
/// The `*const T` and `*mut T` types also define the [`offset`] method, for
/// pointer math.
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
///
/// # Common ways to create raw pointers
///
/// ## 1. Coerce a reference (`&T`) or mutable reference (`&mut T`).
///
/// ```
/// let my_num: i32 = 10;
/// let my_num_ptr: *const i32 = &my_num;
/// let mut my_speed: i32 = 88;
/// let my_speed_ptr: *mut i32 = &mut my_speed;
/// ```
///
/// To get a pointer to a boxed value, dereference the box:
///
/// ```
/// let my_num: Box<i32> = Box::new(10);
/// let my_num_ptr: *const i32 = &*my_num;
/// let mut my_speed: Box<i32> = Box::new(88);
/// let my_speed_ptr: *mut i32 = &mut *my_speed;
/// ```
///
/// This does not take ownership of the original allocation
/// and requires no resource management later,
/// but you must not use the pointer after its lifetime.
///
/// ## 2. Consume a box (`Box<T>`).
///
G
Guillaume Gomez 已提交
434
/// The [`into_raw`] function consumes a box and returns
435 436 437 438 439 440 441 442 443 444 445 446 447
/// the raw pointer. It doesn't destroy `T` or deallocate any memory.
///
/// ```
/// let my_speed: Box<i32> = Box::new(88);
/// let my_speed: *mut i32 = Box::into_raw(my_speed);
///
/// // By taking ownership of the original `Box<T>` though
/// // we are obligated to put it together later to be destroyed.
/// unsafe {
///     drop(Box::from_raw(my_speed));
/// }
/// ```
///
G
Guillaume Gomez 已提交
448
/// Note that here the call to [`drop`] is for clarity - it indicates
449 450
/// that we are done with the given value and it should be destroyed.
///
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
/// ## 3. Create it using `ptr::addr_of!`
///
/// Instead of coercing a reference to a raw pointer, you can use the macros
/// [`ptr::addr_of!`] (for `*const T`) and [`ptr::addr_of_mut!`] (for `*mut T`).
/// These macros allow you to create raw pointers to fields to which you cannot
/// create a reference (without causing undefined behaviour), such as an
/// unaligned field. This might be necessary if packed structs or uninitialized
/// memory is involved.
///
/// ```
/// #[derive(Debug, Default, Copy, Clone)]
/// #[repr(C, packed)]
/// struct S {
///     aligned: u8,
///     unaligned: u32,
/// }
/// let s = S::default();
/// let p = std::ptr::addr_of!(s.unaligned); // not allowed with coercion
/// ```
///
/// ## 4. Get it from C.
472 473
///
/// ```
474
/// # #![feature(rustc_private)]
475 476 477 478
/// extern crate libc;
///
/// use std::mem;
///
479 480 481 482
/// unsafe {
///     let my_num: *mut i32 = libc::malloc(mem::size_of::<i32>()) as *mut i32;
///     if my_num.is_null() {
///         panic!("failed to allocate memory");
483
///     }
484
///     libc::free(my_num as *mut libc::c_void);
485 486 487 488 489 490 491
/// }
/// ```
///
/// Usually you wouldn't literally use `malloc` and `free` from Rust,
/// but C APIs hand out a lot of pointers generally, so are a common source
/// of raw pointers in Rust.
///
492 493
/// [`null`]: ptr::null
/// [`null_mut`]: ptr::null_mut
494 495
/// [`is_null`]: pointer::is_null
/// [`offset`]: pointer::offset
496 497 498
/// [`into_raw`]: Box::into_raw
/// [`drop`]: mem::drop
/// [`write`]: ptr::write
499
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
500
mod prim_pointer {}
501

J
Joshua Nelson 已提交
502 503 504
#[doc(alias = "[]")]
#[doc(alias = "[T;N]")] // unfortunately, rustdoc doesn't have fuzzy search for aliases
#[doc(alias = "[T; N]")]
505
#[doc(primitive = "array")]
506
/// A fixed-size array, denoted `[T; N]`, for the element type, `T`, and the
K
Keegan McAllister 已提交
507
/// non-negative compile-time constant size, `N`.
508
///
K
Keegan McAllister 已提交
509
/// There are two syntactic forms for creating an array:
510
///
511
/// * A list with each element, i.e., `[x, y, z]`.
K
Keegan McAllister 已提交
512
/// * A repeat expression `[x; N]`, which produces an array with `N` copies of `x`.
513
///   The type of `x` must be [`Copy`].
514
///
W
William Woodruff 已提交
515 516 517
/// Note that `[expr; 0]` is allowed, and produces an empty array.
/// This will still evaluate `expr`, however, and immediately drop the resulting value, so
/// be mindful of side effects.
518
///
519
/// Arrays of *any* size implement the following traits if the element type allows it:
520
///
521 522
/// - [`Copy`]
/// - [`Clone`]
523
/// - [`Debug`]
524
/// - [`IntoIterator`] (implemented for `[T; N]`, `&[T; N]` and `&mut [T; N]`)
525 526 527 528
/// - [`PartialEq`], [`PartialOrd`], [`Eq`], [`Ord`]
/// - [`Hash`]
/// - [`AsRef`], [`AsMut`]
/// - [`Borrow`], [`BorrowMut`]
K
Keegan McAllister 已提交
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
K
Keegan McAllister 已提交
532
/// statically generated up to size 32.
533
///
K
Keegan McAllister 已提交
534 535 536 537
/// Arrays coerce to [slices (`[T]`)][slice], so a slice method may be called on
/// an array. Indeed, this provides most of the API for working with arrays.
/// Slices have a dynamic size and do not coerce to arrays.
///
L
Lzu Tao 已提交
538
/// You can move elements out of an array with a [slice pattern]. If you want
539
/// one element, see [`mem::replace`].
540 541 542
///
/// # Examples
///
P
Pietro Albini 已提交
543
/// ```
544 545 546 547 548 549 550 551
/// let mut array: [i32; 3] = [0; 3];
///
/// array[1] = 1;
/// array[2] = 2;
///
/// assert_eq!([1, 2], &array[1..]);
///
/// // This loop prints: 0 1 2
552
/// for x in array {
553 554
///     print!("{} ", x);
/// }
K
Keegan McAllister 已提交
555 556
/// ```
///
557
/// You can also iterate over reference to the array's elements:
K
Keegan McAllister 已提交
558 559
///
/// ```
560
/// let array: [i32; 3] = [0; 3];
K
Keegan McAllister 已提交
561 562
///
/// for x in &array { }
563 564
/// ```
///
L
Lzu Tao 已提交
565
/// You can use a [slice pattern] to move elements out of an array:
Y
Yuki Okushi 已提交
566 567 568 569 570 571 572 573 574
///
/// ```
/// fn move_away(_: String) { /* Do interesting things. */ }
///
/// let [john, roa] = ["John".to_string(), "Roa".to_string()];
/// move_away(john);
/// move_away(roa);
/// ```
///
575 576 577
/// # Editions
///
/// Prior to Rust 1.53, arrays did not implement `IntoIterator` by value, so the method call
578 579 580 581
/// `array.into_iter()` auto-referenced into a slice iterator. Right now, the old behavior
/// is preserved in the 2015 and 2018 editions of Rust for compatibility, ignoring
/// `IntoIterator` by value. In the future, the behavior on the 2015 and 2018 edition
/// might be made consistent to the behavior of later editions.
582
///
P
Pietro Albini 已提交
583
/// ```rust,edition2018
M
Mara Bos 已提交
584 585
/// // Rust 2015 and 2018:
///
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
/// # #![allow(array_into_iter)] // override our `deny(warnings)`
/// let array: [i32; 3] = [0; 3];
///
/// // This creates a slice iterator, producing references to each value.
/// for item in array.into_iter().enumerate() {
///     let (i, x): (usize, &i32) = item;
///     println!("array[{}] = {}", i, x);
/// }
///
/// // The `array_into_iter` lint suggests this change for future compatibility:
/// for item in array.iter().enumerate() {
///     let (i, x): (usize, &i32) = item;
///     println!("array[{}] = {}", i, x);
/// }
///
/// // You can explicitly iterate an array by value using
/// // `IntoIterator::into_iter` or `std::array::IntoIter::new`:
/// for item in IntoIterator::into_iter(array).enumerate() {
///     let (i, x): (usize, i32) = item;
///     println!("array[{}] = {}", i, x);
/// }
/// ```
///
M
Mara Bos 已提交
609
/// Starting in the 2021 edition, `array.into_iter()` uses `IntoIterator` normally to iterate
610 611
/// by value, and `iter()` should be used to iterate by reference like previous editions.
///
M
Mara Bos 已提交
612 613 614 615
#[cfg_attr(bootstrap, doc = "```rust,edition2021,ignore")]
#[cfg_attr(not(bootstrap), doc = "```rust,edition2021")]
/// // Rust 2021:
///
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
/// let array: [i32; 3] = [0; 3];
///
/// // This iterates by reference:
/// for item in array.iter().enumerate() {
///     let (i, x): (usize, &i32) = item;
///     println!("array[{}] = {}", i, x);
/// }
///
/// // This iterates by value:
/// for item in array.into_iter().enumerate() {
///     let (i, x): (usize, i32) = item;
///     println!("array[{}] = {}", i, x);
/// }
/// ```
///
631 632 633 634 635 636 637
/// Future language versions might start treating the `array.into_iter()`
/// syntax on editions 2015 and 2018 the same as on edition 2021. So code using
/// those older editions should still be written with this change in mind, to
/// prevent breakage in the future. The safest way to accomplish this is to
/// avoid the `into_iter` syntax on those editions. If an edition update is not
/// viable/desired, there are multiple alternatives:
/// * use `iter`, equivalent to the old behavior, creating references
M
Mara Bos 已提交
638
/// * use [`IntoIterator::into_iter`], equivalent to the post-2021 behavior (Rust 1.53+)
639 640 641
/// * replace `for ... in array.into_iter() {` with `for ... in array {`,
///   equivalent to the post-2021 behavior (Rust 1.53+)
///
P
Pietro Albini 已提交
642
/// ```rust,edition2018
M
Mara Bos 已提交
643
/// // Rust 2015 and 2018:
644 645 646 647 648 649 650 651 652 653
///
/// let array: [i32; 3] = [0; 3];
///
/// // This iterates by reference:
/// for item in array.iter() {
///     let x: &i32 = item;
///     println!("{}", x);
/// }
///
/// // This iterates by value:
M
Mara Bos 已提交
654
/// for item in IntoIterator::into_iter(array) {
655 656 657 658 659 660 661 662 663 664 665 666
///     let x: i32 = item;
///     println!("{}", x);
/// }
///
/// // This iterates by value:
/// for item in array {
///     let x: i32 = item;
///     println!("{}", x);
/// }
///
/// // IntoIter can also start a chain.
/// // This iterates by value:
M
Mara Bos 已提交
667
/// for item in IntoIterator::into_iter(array).enumerate() {
668 669 670 671 672
///     let (i, x): (usize, i32) = item;
///     println!("array[{}] = {}", i, x);
/// }
/// ```
///
673
/// [slice]: prim@slice
674 675 676 677
/// [`Debug`]: fmt::Debug
/// [`Hash`]: hash::Hash
/// [`Borrow`]: borrow::Borrow
/// [`BorrowMut`]: borrow::BorrowMut
L
Lzu Tao 已提交
678
/// [slice pattern]: ../reference/patterns.html#slice-patterns
679
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
680
mod prim_array {}
681 682

#[doc(primitive = "slice")]
G
Guillaume Gomez 已提交
683 684 685
#[doc(alias = "[")]
#[doc(alias = "]")]
#[doc(alias = "[]")]
686
/// A dynamically-sized view into a contiguous sequence, `[T]`. Contiguous here
A
Andre Bogus 已提交
687
/// means that elements are laid out so that every element is the same
688
/// distance from its neighbors.
689
///
C
Camelid 已提交
690
/// *[See also the `std::slice` module](crate::slice).*
M
Michael Lamparski 已提交
691
///
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
/// Slices are a view into a block of memory represented as a pointer and a
/// length.
///
/// ```
/// // slicing a Vec
/// let vec = vec![1, 2, 3];
/// let int_slice = &vec[..];
/// // coercing an array to a slice
/// let str_slice: &[&str] = &["one", "two", "three"];
/// ```
///
/// Slices are either mutable or shared. The shared slice type is `&[T]`,
/// while the mutable slice type is `&mut [T]`, where `T` represents the element
/// type. For example, you can mutate the block of memory that a mutable slice
/// points to:
///
/// ```
709 710
/// let mut x = [1, 2, 3];
/// let x = &mut x[..]; // Take a full slice of `x`.
711 712 713
/// x[1] = 7;
/// assert_eq!(x, &[1, 7, 3]);
/// ```
714 715 716 717
///
/// As slices store the length of the sequence they refer to, they have twice
/// the size of pointers to [`Sized`](marker/trait.Sized.html) types.
/// Also see the reference on
L
Leon Matthes 已提交
718
/// [dynamically sized types](../reference/dynamically-sized-types.html).
719 720
///
/// ```
L
Leon Matthes 已提交
721
/// # use std::rc::Rc;
722 723 724 725 726 727
/// let pointer_size = std::mem::size_of::<&u8>();
/// assert_eq!(2 * pointer_size, std::mem::size_of::<&[u8]>());
/// assert_eq!(2 * pointer_size, std::mem::size_of::<*const [u8]>());
/// assert_eq!(2 * pointer_size, std::mem::size_of::<Box<[u8]>>());
/// assert_eq!(2 * pointer_size, std::mem::size_of::<Rc<[u8]>>());
/// ```
728
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
729
mod prim_slice {}
730 731 732

#[doc(primitive = "str")]
//
S
Steve Klabnik 已提交
733
/// String slices.
734
///
C
Camelid 已提交
735
/// *[See also the `std::str` module](crate::str).*
736
///
S
Steve Klabnik 已提交
737 738 739 740
/// The `str` type, also called a 'string slice', is the most primitive string
/// type. It is usually seen in its borrowed form, `&str`. It is also the type
/// of string literals, `&'static str`.
///
741
/// String slices are always valid UTF-8.
742 743 744
///
/// # Examples
///
S
Steve Klabnik 已提交
745
/// String literals are string slices:
746 747
///
/// ```
S
Steve Klabnik 已提交
748 749 750 751
/// let hello = "Hello, world!";
///
/// // with an explicit type annotation
/// let hello: &'static str = "Hello, world!";
752 753
/// ```
///
S
Steve Klabnik 已提交
754 755
/// They are `'static` because they're stored directly in the final binary, and
/// so will be valid for the `'static` duration.
756
///
S
Steve Klabnik 已提交
757 758 759
/// # Representation
///
/// A `&str` is made up of two components: a pointer to some bytes, and a
P
projektir 已提交
760
/// length. You can look at these with the [`as_ptr`] and [`len`] methods:
761 762
///
/// ```
S
Steve Klabnik 已提交
763 764
/// use std::slice;
/// use std::str;
765
///
S
Steve Klabnik 已提交
766 767 768 769
/// let story = "Once upon a time...";
///
/// let ptr = story.as_ptr();
/// let len = story.len();
770
///
S
Steve Klabnik 已提交
771
/// // story has nineteen bytes
S
Steve Klabnik 已提交
772
/// assert_eq!(19, len);
773
///
774
/// // We can re-build a str out of ptr and len. This is all unsafe because
S
Steve Klabnik 已提交
775 776 777 778
/// // we are responsible for making sure the two components are valid:
/// let s = unsafe {
///     // First, we build a &[u8]...
///     let slice = slice::from_raw_parts(ptr, len);
779
///
S
Steve Klabnik 已提交
780 781 782 783 784 785
///     // ... and then convert that slice into a string slice
///     str::from_utf8(slice)
/// };
///
/// assert_eq!(s, Ok(story));
/// ```
786
///
787 788
/// [`as_ptr`]: str::as_ptr
/// [`len`]: str::len
789 790
///
/// Note: This example shows the internals of `&str`. `unsafe` should not be
791
/// used to get a string slice under normal circumstances. Use `as_str`
792
/// instead.
793
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
794
mod prim_str {}
795 796

#[doc(primitive = "tuple")]
G
Guillaume Gomez 已提交
797 798 799
#[doc(alias = "(")]
#[doc(alias = ")")]
#[doc(alias = "()")]
800 801 802
//
/// A finite heterogeneous sequence, `(T, U, ..)`.
///
S
Steve Klabnik 已提交
803
/// Let's cover each of those in turn:
804
///
S
Steve Klabnik 已提交
805 806 807 808 809 810 811
/// Tuples are *finite*. In other words, a tuple has a length. Here's a tuple
/// of length `3`:
///
/// ```
/// ("hello", 5, 'c');
/// ```
///
812 813 814
/// 'Length' is also sometimes called 'arity' here; each tuple of a different
/// length is a different, distinct type.
///
S
Steve Klabnik 已提交
815 816 817
/// Tuples are *heterogeneous*. This means that each element of the tuple can
/// have a different type. In that tuple above, it has the type:
///
818 819
/// ```
/// # let _:
S
Steve Klabnik 已提交
820
/// (&'static str, i32, char)
821
/// # = ("hello", 5, 'c');
S
Steve Klabnik 已提交
822 823 824 825 826 827 828 829 830 831 832 833 834
/// ```
///
/// Tuples are a *sequence*. This means that they can be accessed by position;
/// this is called 'tuple indexing', and it looks like this:
///
/// ```rust
/// let tuple = ("hello", 5, 'c');
///
/// assert_eq!(tuple.0, "hello");
/// assert_eq!(tuple.1, 5);
/// assert_eq!(tuple.2, 'c');
/// ```
///
835 836 837 838
/// The sequential nature of the tuple applies to its implementations of various
/// traits.  For example, in `PartialOrd` and `Ord`, the elements are compared
/// sequentially until the first non-equal set is found.
///
S
Steve Klabnik 已提交
839
/// For more about tuples, see [the book](../book/ch03-02-data-types.html#the-tuple-type).
S
Steve Klabnik 已提交
840 841
///
/// # Trait implementations
842
///
843 844
/// If every type inside a tuple implements one of the following traits, then a
/// tuple itself also implements it.
845
///
S
Steve Klabnik 已提交
846
/// * [`Clone`]
847
/// * [`Copy`]
S
Steve Klabnik 已提交
848 849 850 851 852 853 854 855
/// * [`PartialEq`]
/// * [`Eq`]
/// * [`PartialOrd`]
/// * [`Ord`]
/// * [`Debug`]
/// * [`Default`]
/// * [`Hash`]
///
856 857
/// [`Debug`]: fmt::Debug
/// [`Hash`]: hash::Hash
858
///
859
/// Due to a temporary restriction in Rust's type system, these traits are only
O
Oliver Middleton 已提交
860
/// implemented on tuples of arity 12 or less. In the future, this may change.
861
///
862 863
/// # Examples
///
S
Steve Klabnik 已提交
864
/// Basic usage:
865 866
///
/// ```
S
Steve Klabnik 已提交
867
/// let tuple = ("hello", 5, 'c');
868
///
S
Steve Klabnik 已提交
869
/// assert_eq!(tuple.0, "hello");
870 871
/// ```
///
S
Steve Klabnik 已提交
872 873
/// Tuples are often used as a return type when you want to return more than
/// one value:
874 875
///
/// ```
S
Steve Klabnik 已提交
876 877 878 879 880 881 882 883 884 885 886
/// fn calculate_point() -> (i32, i32) {
///     // Don't do a calculation, that's not the point of the example
///     (4, 5)
/// }
///
/// let point = calculate_point();
///
/// assert_eq!(point.0, 4);
/// assert_eq!(point.1, 5);
///
/// // Combining this with patterns can be nicer.
887
///
S
Steve Klabnik 已提交
888
/// let (x, y) = calculate_point();
889
///
S
Steve Klabnik 已提交
890 891
/// assert_eq!(x, 4);
/// assert_eq!(y, 5);
892 893
/// ```
///
894
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
895
mod prim_tuple {}
896 897

#[doc(primitive = "f32")]
898 899 900 901
/// A 32-bit floating point type (specifically, the "binary32" type defined in IEEE 754-2008).
///
/// This type can represent a wide range of decimal numbers, like `3.5`, `27`,
/// `-113.75`, `0.0078125`, `34359738368`, `0`, `-1`. So unlike integer types
902 903
/// (such as `i32`), floating point types can represent non-integer numbers,
/// too.
904 905 906 907 908 909
///
/// However, being able to represent this wide range of numbers comes at the
/// cost of precision: floats can only represent some of the real numbers and
/// calculation with floats round to a nearby representable number. For example,
/// `5.0` and `1.0` can be exactly represented as `f32`, but `1.0 / 5.0` results
/// in `0.20000000298023223876953125` since `0.2` cannot be exactly represented
C
Camelid 已提交
910
/// as `f32`. Note, however, that printing floats with `println` and friends will
911 912 913
/// often discard insignificant digits: `println!("{}", 1.0f32 / 5.0f32)` will
/// print `0.2`.
///
J
Jubilee Young 已提交
914
/// Additionally, `f32` can represent some special values:
915
///
916
/// - −0.0: IEEE 754 floating point numbers have a bit that indicates their sign, so −0.0 is a
917 918
///   possible value. For comparison −0.0 = +0.0, but floating point operations can carry
///   the sign bit through arithmetic operations. This means −0.0 × +0.0 produces −0.0 and
919
///   a negative number rounded to a value smaller than a float can represent also produces −0.0.
920
/// - [∞](#associatedconstant.INFINITY) and
921
///   [−∞](#associatedconstant.NEG_INFINITY): these result from calculations
922 923 924 925 926 927 928 929 930
///   like `1.0 / 0.0`.
/// - [NaN (not a number)](#associatedconstant.NAN): this value results from
///   calculations like `(-1.0).sqrt()`. NaN has some potentially unexpected
///   behavior: it is unequal to any float, including itself! It is also neither
///   smaller nor greater than any float, making it impossible to sort. Lastly,
///   it is considered infectious as almost all calculations where one of the
///   operands is NaN will also result in NaN.
///
/// For more information on floating point numbers, see [Wikipedia][wikipedia].
931
///
C
Camelid 已提交
932
/// *[See also the `std::f32::consts` module](crate::f32::consts).*
933
///
934
/// [wikipedia]: https://en.wikipedia.org/wiki/Single-precision_floating-point_format
935
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
936
mod prim_f32 {}
937 938

#[doc(primitive = "f64")]
939 940
/// A 64-bit floating point type (specifically, the "binary64" type defined in IEEE 754-2008).
///
941
/// This type is very similar to [`f32`], but has increased
942
/// precision by using twice as many bits. Please see [the documentation for
J
Joshua Nelson 已提交
943
/// `f32`][`f32`] or [Wikipedia on double precision
944
/// values][wikipedia] for more information.
945
///
C
Camelid 已提交
946
/// *[See also the `std::f64::consts` module](crate::f64::consts).*
947
///
948
/// [`f32`]: prim@f32
949
/// [wikipedia]: https://en.wikipedia.org/wiki/Double-precision_floating-point_format
950
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
951
mod prim_f64 {}
952 953 954

#[doc(primitive = "i8")]
//
B
Brian Anderson 已提交
955
/// The 8-bit signed integer type.
956
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
957
mod prim_i8 {}
958 959 960

#[doc(primitive = "i16")]
//
B
Brian Anderson 已提交
961
/// The 16-bit signed integer type.
962
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
963
mod prim_i16 {}
964 965 966

#[doc(primitive = "i32")]
//
B
Brian Anderson 已提交
967
/// The 32-bit signed integer type.
968
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
969
mod prim_i32 {}
970 971 972

#[doc(primitive = "i64")]
//
B
Brian Anderson 已提交
973
/// The 64-bit signed integer type.
974
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
975
mod prim_i64 {}
976

977 978 979
#[doc(primitive = "i128")]
//
/// The 128-bit signed integer type.
M
Mark Rousskov 已提交
980 981
#[stable(feature = "i128", since = "1.26.0")]
mod prim_i128 {}
982

983 984
#[doc(primitive = "u8")]
//
B
Brian Anderson 已提交
985
/// The 8-bit unsigned integer type.
986
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
987
mod prim_u8 {}
988 989 990

#[doc(primitive = "u16")]
//
B
Brian Anderson 已提交
991
/// The 16-bit unsigned integer type.
992
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
993
mod prim_u16 {}
994 995 996

#[doc(primitive = "u32")]
//
B
Brian Anderson 已提交
997
/// The 32-bit unsigned integer type.
998
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
999
mod prim_u32 {}
1000 1001 1002

#[doc(primitive = "u64")]
//
B
Brian Anderson 已提交
1003
/// The 64-bit unsigned integer type.
1004
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
1005
mod prim_u64 {}
1006

1007 1008 1009
#[doc(primitive = "u128")]
//
/// The 128-bit unsigned integer type.
M
Mark Rousskov 已提交
1010 1011
#[stable(feature = "i128", since = "1.26.0")]
mod prim_u128 {}
1012

1013 1014
#[doc(primitive = "isize")]
//
B
Brian Anderson 已提交
1015
/// The pointer-sized signed integer type.
1016
///
1017 1018 1019
/// The size of this primitive is how many bytes it takes to reference any
/// location in memory. For example, on a 32 bit target, this is 4 bytes
/// and on a 64 bit target, this is 8 bytes.
1020
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
1021
mod prim_isize {}
1022 1023 1024

#[doc(primitive = "usize")]
//
1025
/// The pointer-sized unsigned integer type.
1026
///
1027 1028 1029
/// The size of this primitive is how many bytes it takes to reference any
/// location in memory. For example, on a 32 bit target, this is 4 bytes
/// and on a 64 bit target, this is 8 bytes.
1030
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
1031
mod prim_usize {}
1032 1033

#[doc(primitive = "reference")]
G
Guillaume Gomez 已提交
1034
#[doc(alias = "&")]
1035
#[doc(alias = "&mut")]
1036 1037 1038 1039 1040 1041
//
/// References, both shared and mutable.
///
/// A reference represents a borrow of some owned value. You can get one by using the `&` or `&mut`
/// operators on a value, or by using a `ref` or `ref mut` pattern.
///
1042
/// For those familiar with pointers, a reference is just a pointer that is assumed to be
R
Ralf Jung 已提交
1043 1044
/// aligned, not null, and pointing to memory containing a valid value of `T` - for example,
/// `&bool` can only point to an allocation containing the integer values `1` (`true`) or `0`
R
Ralf Jung 已提交
1045 1046
/// (`false`), but creating a `&bool` that points to an allocation containing
/// the value `3` causes undefined behaviour.
R
Ralf Jung 已提交
1047
/// In fact, `Option<&T>` has the same memory representation as a
1048
/// nullable but aligned pointer, and can be passed across FFI boundaries as such.
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
///
/// In most cases, references can be used much like the original value. Field access, method
/// calling, and indexing work the same (save for mutability rules, of course). In addition, the
/// comparison operators transparently defer to the referent's implementation, allowing references
/// to be compared the same as owned values.
///
/// References have a lifetime attached to them, which represents the scope for which the borrow is
/// valid. A lifetime is said to "outlive" another one if its representative scope is as long or
/// longer than the other. The `'static` lifetime is the longest lifetime, which represents the
/// total life of the program. For example, string literals have a `'static` lifetime because the
/// text data is embedded into the binary of the program, rather than in an allocation that needs
/// to be dynamically managed.
///
/// `&mut T` references can be freely coerced into `&T` references with the same referent type, and
/// references with longer lifetimes can be freely coerced into references with shorter ones.
///
1065
/// Reference equality by address, instead of comparing the values pointed to, is accomplished via
L
Lucas Lois 已提交
1066
/// implicit reference-pointer coercion and raw pointer equality via [`ptr::eq`], while
1067
/// [`PartialEq`] compares values.
L
Lucas Lois 已提交
1068
///
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
/// ```
/// use std::ptr;
///
/// let five = 5;
/// let other_five = 5;
/// let five_ref = &five;
/// let same_five_ref = &five;
/// let other_five_ref = &other_five;
///
/// assert!(five_ref == same_five_ref);
/// assert!(five_ref == other_five_ref);
///
/// assert!(ptr::eq(five_ref, same_five_ref));
/// assert!(!ptr::eq(five_ref, other_five_ref));
/// ```
L
Lucas Lois 已提交
1084
///
1085 1086 1087
/// For more information on how to use references, see [the book's section on "References and
/// Borrowing"][book-refs].
///
1088
/// [book-refs]: ../book/ch04-02-references-and-borrowing.html
1089
///
1090
/// # Trait implementations
L
Lucas Lois 已提交
1091
///
1092 1093 1094 1095 1096 1097 1098 1099
/// The following traits are implemented for all `&T`, regardless of the type of its referent:
///
/// * [`Copy`]
/// * [`Clone`] \(Note that this will not defer to `T`'s `Clone` implementation if it exists!)
/// * [`Deref`]
/// * [`Borrow`]
/// * [`Pointer`]
///
1100 1101 1102
/// [`Deref`]: ops::Deref
/// [`Borrow`]: borrow::Borrow
/// [`Pointer`]: fmt::Pointer
1103 1104 1105 1106 1107 1108 1109 1110
///
/// `&mut T` references get all of the above except `Copy` and `Clone` (to prevent creating
/// multiple simultaneous mutable borrows), plus the following, regardless of the type of its
/// referent:
///
/// * [`DerefMut`]
/// * [`BorrowMut`]
///
1111 1112
/// [`DerefMut`]: ops::DerefMut
/// [`BorrowMut`]: borrow::BorrowMut
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
///
/// The following traits are implemented on `&T` references if the underlying `T` also implements
/// that trait:
///
/// * All the traits in [`std::fmt`] except [`Pointer`] and [`fmt::Write`]
/// * [`PartialOrd`]
/// * [`Ord`]
/// * [`PartialEq`]
/// * [`Eq`]
/// * [`AsRef`]
/// * [`Fn`] \(in addition, `&T` references get [`FnMut`] and [`FnOnce`] if `T: Fn`)
/// * [`Hash`]
/// * [`ToSocketAddrs`]
///
1127 1128 1129 1130
/// [`std::fmt`]: fmt
/// ['Pointer`]: fmt::Pointer
/// [`Hash`]: hash::Hash
/// [`ToSocketAddrs`]: net::ToSocketAddrs
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
///
/// `&mut T` references get all of the above except `ToSocketAddrs`, plus the following, if `T`
/// implements that trait:
///
/// * [`AsMut`]
/// * [`FnMut`] \(in addition, `&mut T` references get [`FnOnce`] if `T: FnMut`)
/// * [`fmt::Write`]
/// * [`Iterator`]
/// * [`DoubleEndedIterator`]
/// * [`ExactSizeIterator`]
/// * [`FusedIterator`]
/// * [`TrustedLen`]
/// * [`Send`] \(note that `&T` references only get `Send` if `T: Sync`)
/// * [`io::Write`]
/// * [`Read`]
/// * [`Seek`]
/// * [`BufRead`]
///
1149 1150 1151 1152 1153
/// [`FusedIterator`]: iter::FusedIterator
/// [`TrustedLen`]: iter::TrustedLen
/// [`Seek`]: io::Seek
/// [`BufRead`]: io::BufRead
/// [`Read`]: io::Read
1154 1155 1156 1157 1158 1159
///
/// Note that due to method call deref coercion, simply calling a trait method will act like they
/// work on references as well as they do on owned values! The implementations described here are
/// meant for generic contexts, where the final type `T` is a type parameter or otherwise not
/// locally known.
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
1160
mod prim_ref {}
1161 1162 1163 1164 1165 1166 1167

#[doc(primitive = "fn")]
//
/// Function pointers, like `fn(usize) -> bool`.
///
/// *See also the traits [`Fn`], [`FnMut`], and [`FnOnce`].*
///
1168 1169 1170
/// [`Fn`]: ops::Fn
/// [`FnMut`]: ops::FnMut
/// [`FnOnce`]: ops::FnOnce
1171
///
1172
/// Function pointers are pointers that point to *code*, not data. They can be called
R
Ralf Jung 已提交
1173 1174 1175
/// just like functions. Like references, function pointers are, among other things, assumed to
/// not be null, so if you want to pass a function pointer over FFI and be able to accommodate null
/// pointers, make your type `Option<fn()>` with your required signature.
1176
///
1177 1178
/// ### Safety
///
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
/// Plain function pointers are obtained by casting either plain functions, or closures that don't
/// capture an environment:
///
/// ```
/// fn add_one(x: usize) -> usize {
///     x + 1
/// }
///
/// let ptr: fn(usize) -> usize = add_one;
/// assert_eq!(ptr(5), 6);
///
/// let clos: fn(usize) -> usize = |x| x + 5;
/// assert_eq!(clos(5), 10);
/// ```
///
/// In addition to varying based on their signature, function pointers come in two flavors: safe
/// and unsafe. Plain `fn()` function pointers can only point to safe functions,
/// while `unsafe fn()` function pointers can point to safe or unsafe functions.
///
/// ```
/// fn add_one(x: usize) -> usize {
///     x + 1
/// }
///
/// unsafe fn add_one_unsafely(x: usize) -> usize {
///     x + 1
/// }
///
/// let safe_ptr: fn(usize) -> usize = add_one;
///
/// //ERROR: mismatched types: expected normal fn, found unsafe fn
/// //let bad_ptr: fn(usize) -> usize = add_one_unsafely;
///
/// let unsafe_ptr: unsafe fn(usize) -> usize = add_one_unsafely;
/// let really_safe_ptr: unsafe fn(usize) -> usize = add_one;
/// ```
///
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
/// ### ABI
///
/// On top of that, function pointers can vary based on what ABI they use. This
/// is achieved by adding the `extern` keyword before the type, followed by the
/// ABI in question. The default ABI is "Rust", i.e., `fn()` is the exact same
/// type as `extern "Rust" fn()`. A pointer to a function with C ABI would have
/// type `extern "C" fn()`.
///
/// `extern "ABI" { ... }` blocks declare functions with ABI "ABI". The default
/// here is "C", i.e., functions declared in an `extern {...}` block have "C"
/// ABI.
///
/// For more information and a list of supported ABIs, see [the nomicon's
/// section on foreign calling conventions][nomicon-abi].
1230
///
1231 1232
/// [nomicon-abi]: ../nomicon/ffi.html#foreign-calling-conventions
///
1233
/// ### Variadic functions
1234 1235
///
/// Extern function declarations with the "C" or "cdecl" ABIs can also be *variadic*, allowing them
1236
/// to be called with a variable number of arguments. Normal Rust functions, even those with an
1237 1238 1239 1240 1241
/// `extern "ABI"`, cannot be variadic. For more information, see [the nomicon's section on
/// variadic functions][nomicon-variadic].
///
/// [nomicon-variadic]: ../nomicon/ffi.html#variadic-functions
///
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271
/// ### Creating function pointers
///
/// When `bar` is the name of a function, then the expression `bar` is *not* a
/// function pointer. Rather, it denotes a value of an unnameable type that
/// uniquely identifies the function `bar`. The value is zero-sized because the
/// type already identifies the function. This has the advantage that "calling"
/// the value (it implements the `Fn*` traits) does not require dynamic
/// dispatch.
///
/// This zero-sized type *coerces* to a regular function pointer. For example:
///
/// ```rust
/// use std::mem;
///
/// fn bar(x: i32) {}
///
/// let not_bar_ptr = bar; // `not_bar_ptr` is zero-sized, uniquely identifying `bar`
/// assert_eq!(mem::size_of_val(&not_bar_ptr), 0);
///
/// let bar_ptr: fn(i32) = not_bar_ptr; // force coercion to function pointer
/// assert_eq!(mem::size_of_val(&bar_ptr), mem::size_of::<usize>());
///
/// let footgun = &bar; // this is a shared reference to the zero-sized type identifying `bar`
/// ```
///
/// The last line shows that `&bar` is not a function pointer either. Rather, it
/// is a reference to the function-specific ZST. `&bar` is basically never what you
/// want when `bar` is a function.
///
/// ### Traits
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
///
/// Function pointers implement the following traits:
///
/// * [`Clone`]
/// * [`PartialEq`]
/// * [`Eq`]
/// * [`PartialOrd`]
/// * [`Ord`]
/// * [`Hash`]
/// * [`Pointer`]
/// * [`Debug`]
///
1284 1285
/// [`Hash`]: hash::Hash
/// [`Pointer`]: fmt::Pointer
1286 1287 1288 1289 1290 1291 1292 1293 1294
///
/// Due to a temporary restriction in Rust's type system, these traits are only implemented on
/// functions that take 12 arguments or less, with the `"Rust"` and `"C"` ABIs. In the future, this
/// may change.
///
/// In addition, function pointers of *any* signature, ABI, or safety are [`Copy`], and all *safe*
/// function pointers implement [`Fn`], [`FnMut`], and [`FnOnce`]. This works because these traits
/// are specially known to the compiler.
#[stable(feature = "rust1", since = "1.0.0")]
M
Mark Rousskov 已提交
1295
mod prim_fn {}