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