1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #[doc(primitive = "bool")]
12 #[doc(alias = "true")]
13 #[doc(alias = "false")]
17 /// The `bool` represents a value, which could only be either `true` or `false`. If you cast
18 /// a `bool` into an integer, `true` will be 1 and `false` will be 0.
22 /// `bool` implements various traits, such as [`BitAnd`], [`BitOr`], [`Not`], etc.,
23 /// which allow us to perform boolean operations using `&`, `|` and `!`.
25 /// [`if`] always demands a `bool` value. [`assert!`], being an important macro in testing,
26 /// checks whether an expression returns `true`.
29 /// let bool_val = true & false | false;
30 /// assert!(!bool_val);
33 /// [`assert!`]: macro.assert.html
34 /// [`if`]: ../book/first-edition/if.html
35 /// [`BitAnd`]: ops/trait.BitAnd.html
36 /// [`BitOr`]: ops/trait.BitOr.html
37 /// [`Not`]: ops/trait.Not.html
41 /// A trivial example of the usage of `bool`,
44 /// let praise_the_borrow_checker = true;
46 /// // using the `if` conditional
47 /// if praise_the_borrow_checker {
48 /// println!("oh, yeah!");
50 /// println!("what?!!");
53 /// // ... or, a match pattern
54 /// match praise_the_borrow_checker {
55 /// true => println!("keep praising!"),
56 /// false => println!("you should praise!"),
60 /// Also, since `bool` implements the [`Copy`](marker/trait.Copy.html) trait, we don't
61 /// have to worry about the move semantics (just like the integer and float primitives).
63 /// Now an example of `bool` cast to integer type:
66 /// assert_eq!(true as i32, 1);
67 /// assert_eq!(false as i32, 0);
69 #[stable(feature = "rust1", since = "1.0.0")]
72 #[doc(primitive = "never")]
75 /// The `!` type, also called "never".
77 /// `!` represents the type of computations which never resolve to any value at all. For example,
78 /// the [`exit`] function `fn exit(code: i32) -> !` exits the process without ever returning, and
81 /// `break`, `continue` and `return` expressions also have type `!`. For example we are allowed to
85 /// #![feature(never_type)]
86 /// # fn foo() -> u32 {
93 /// Although the `let` is pointless here, it illustrates the meaning of `!`. Since `x` is never
94 /// assigned a value (because `return` returns from the entire function), `x` can be given type
95 /// `!`. We could also replace `return 123` with a `panic!` or a never-ending `loop` and this code
96 /// would still be valid.
98 /// A more realistic usage of `!` is in this code:
101 /// # fn get_a_number() -> Option<u32> { None }
103 /// let num: u32 = match get_a_number() {
104 /// Some(num) => num,
110 /// Both match arms must produce values of type [`u32`], but since `break` never produces a value
111 /// at all we know it can never produce a value which isn't a [`u32`]. This illustrates another
112 /// behaviour of the `!` type - expressions with type `!` will coerce into any other type.
114 /// [`u32`]: primitive.str.html
115 /// [`exit`]: process/fn.exit.html
117 /// # `!` and generics
119 /// ## Infallible errors
121 /// The main place you'll see `!` used explicitly is in generic code. Consider the [`FromStr`]
125 /// trait FromStr: Sized {
127 /// fn from_str(s: &str) -> Result<Self, Self::Err>;
131 /// When implementing this trait for [`String`] we need to pick a type for [`Err`]. And since
132 /// converting a string into a string will never result in an error, the appropriate type is `!`.
133 /// (Currently the type actually used is an enum with no variants, though this is only because `!`
134 /// was added to Rust at a later date and it may change in the future). With an [`Err`] type of
135 /// `!`, if we have to call [`String::from_str`] for some reason the result will be a
136 /// [`Result<String, !>`] which we can unpack like this:
138 /// ```ignore (string-from-str-error-type-is-not-never-yet)
139 /// #[feature(exhaustive_patterns)]
140 /// // NOTE: This does not work today!
141 /// let Ok(s) = String::from_str("hello");
144 /// Since the [`Err`] variant contains a `!`, it can never occur. If the `exhaustive_patterns`
145 /// feature is present this means we can exhaustively match on [`Result<T, !>`] by just taking the
146 /// [`Ok`] variant. This illustrates another behaviour of `!` - it can be used to "delete" certain
147 /// enum variants from generic types like `Result`.
149 /// ## Infinite loops
151 /// While [`Result<T, !>`] is very useful for removing errors, `!` can also be used to remove
152 /// successes as well. If we think of [`Result<T, !>`] as "if this function returns, it has not
153 /// errored," we get a very intuitive idea of [`Result<!, E>`] as well: if the function returns, it
156 /// For example, consider the case of a simple web server, which can be simplified to:
158 /// ```ignore (hypothetical-example)
160 /// let (client, request) = get_request().expect("disconnected");
161 /// let response = request.process();
162 /// response.send(client);
166 /// Currently, this isn't ideal, because we simply panic whenever we fail to get a new connection.
167 /// Instead, we'd like to keep track of this error, like this:
169 /// ```ignore (hypothetical-example)
171 /// match get_request() {
172 /// Err(err) => break err,
173 /// Ok((client, request)) => {
174 /// let response = request.process();
175 /// response.send(client);
181 /// Now, when the server disconnects, we exit the loop with an error instead of panicking. While it
182 /// might be intuitive to simply return the error, we might want to wrap it in a [`Result<!, E>`]
185 /// ```ignore (hypothetical-example)
186 /// fn server_loop() -> Result<!, ConnectionError> {
188 /// let (client, request) = get_request()?;
189 /// let response = request.process();
190 /// response.send(client);
195 /// Now, we can use `?` instead of `match`, and the return type makes a lot more sense: if the loop
196 /// ever stops, it means that an error occurred. We don't even have to wrap the loop in an `Ok`
197 /// because `!` coerces to `Result<!, ConnectionError>` automatically.
199 /// [`String::from_str`]: str/trait.FromStr.html#tymethod.from_str
200 /// [`Result<String, !>`]: result/enum.Result.html
201 /// [`Result<T, !>`]: result/enum.Result.html
202 /// [`Result<!, E>`]: result/enum.Result.html
203 /// [`Ok`]: result/enum.Result.html#variant.Ok
204 /// [`String`]: string/struct.String.html
205 /// [`Err`]: result/enum.Result.html#variant.Err
206 /// [`FromStr`]: str/trait.FromStr.html
210 /// When writing your own traits, `!` should have an `impl` whenever there is an obvious `impl`
211 /// which doesn't `panic!`. As it turns out, most traits can have an `impl` for `!`. Take [`Debug`]
215 /// #![feature(never_type)]
218 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result;
220 /// impl Debug for ! {
221 /// fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
227 /// Once again we're using `!`'s ability to coerce into any other type, in this case
228 /// [`fmt::Result`]. Since this method takes a `&!` as an argument we know that it can never be
229 /// called (because there is no value of type `!` for it to be called with). Writing `*self`
230 /// essentially tells the compiler "We know that this code can never be run, so just treat the
231 /// entire function body as having type [`fmt::Result`]". This pattern can be used a lot when
232 /// implementing traits for `!`. Generally, any trait which only has methods which take a `self`
233 /// parameter should have such an impl.
235 /// On the other hand, one trait which would not be appropriate to implement is [`Default`]:
239 /// fn default() -> Self;
243 /// Since `!` has no values, it has no default value either. It's true that we could write an
244 /// `impl` for this which simply panics, but the same is true for any type (we could `impl
245 /// Default` for (eg.) [`File`] by just making [`default()`] panic.)
247 /// [`fmt::Result`]: fmt/type.Result.html
248 /// [`File`]: fs/struct.File.html
249 /// [`Debug`]: fmt/trait.Debug.html
250 /// [`Default`]: default/trait.Default.html
251 /// [`default()`]: default/trait.Default.html#tymethod.default
253 #[unstable(feature = "never_type", issue = "35121")]
256 #[doc(primitive = "char")]
258 /// A character type.
260 /// The `char` type represents a single character. More specifically, since
261 /// 'character' isn't a well-defined concept in Unicode, `char` is a '[Unicode
262 /// scalar value]', which is similar to, but not the same as, a '[Unicode code
265 /// [Unicode scalar value]: http://www.unicode.org/glossary/#unicode_scalar_value
266 /// [Unicode code point]: http://www.unicode.org/glossary/#code_point
268 /// This documentation describes a number of methods and trait implementations on the
269 /// `char` type. For technical reasons, there is additional, separate
270 /// documentation in [the `std::char` module](char/index.html) as well.
274 /// `char` is always four bytes in size. This is a different representation than
275 /// a given character would have as part of a [`String`]. For example:
278 /// let v = vec!['h', 'e', 'l', 'l', 'o'];
280 /// // five elements times four bytes for each element
281 /// assert_eq!(20, v.len() * std::mem::size_of::<char>());
283 /// let s = String::from("hello");
285 /// // five elements times one byte per element
286 /// assert_eq!(5, s.len() * std::mem::size_of::<u8>());
289 /// [`String`]: string/struct.String.html
291 /// As always, remember that a human intuition for 'character' may not map to
292 /// Unicode's definitions. For example, despite looking similar, the 'é'
293 /// character is one Unicode code point while 'é' is two Unicode code points:
296 /// let mut chars = "é".chars();
297 /// // U+00e9: 'latin small letter e with acute'
298 /// assert_eq!(Some('\u{00e9}'), chars.next());
299 /// assert_eq!(None, chars.next());
301 /// let mut chars = "é".chars();
302 /// // U+0065: 'latin small letter e'
303 /// assert_eq!(Some('\u{0065}'), chars.next());
304 /// // U+0301: 'combining acute accent'
305 /// assert_eq!(Some('\u{0301}'), chars.next());
306 /// assert_eq!(None, chars.next());
309 /// This means that the contents of the first string above _will_ fit into a
310 /// `char` while the contents of the second string _will not_. Trying to create
311 /// a `char` literal with the contents of the second string gives an error:
314 /// error: character literal may only contain one codepoint: 'é'
319 /// Another implication of the 4-byte fixed size of a `char` is that
320 /// per-`char` processing can end up using a lot more memory:
323 /// let s = String::from("love: ❤️");
324 /// let v: Vec<char> = s.chars().collect();
326 /// assert_eq!(12, s.len() * std::mem::size_of::<u8>());
327 /// assert_eq!(32, v.len() * std::mem::size_of::<char>());
329 #[stable(feature = "rust1", since = "1.0.0")]
332 #[doc(primitive = "unit")]
334 /// The `()` type, sometimes called "unit" or "nil".
336 /// The `()` type has exactly one value `()`, and is used when there
337 /// is no other meaningful value that could be returned. `()` is most
338 /// commonly seen implicitly: functions without a `-> ...` implicitly
339 /// have return type `()`, that is, these are equivalent:
342 /// fn long() -> () {}
347 /// The semicolon `;` can be used to discard the result of an
348 /// expression at the end of a block, making the expression (and thus
349 /// the block) evaluate to `()`. For example,
352 /// fn returns_i64() -> i64 {
355 /// fn returns_unit() {
367 #[stable(feature = "rust1", since = "1.0.0")]
370 #[doc(primitive = "pointer")]
372 /// Raw, unsafe pointers, `*const T`, and `*mut T`.
374 /// *[See also the `std::ptr` module](ptr/index.html).*
376 /// Working with raw pointers in Rust is uncommon,
377 /// typically limited to a few patterns.
379 /// Use the [`null`] and [`null_mut`] functions to create null pointers, and the
380 /// [`is_null`] method of the `*const T` and `*mut T` types to check for null.
381 /// The `*const T` and `*mut T` types also define the [`offset`] method, for
384 /// # Common ways to create raw pointers
386 /// ## 1. Coerce a reference (`&T`) or mutable reference (`&mut T`).
389 /// let my_num: i32 = 10;
390 /// let my_num_ptr: *const i32 = &my_num;
391 /// let mut my_speed: i32 = 88;
392 /// let my_speed_ptr: *mut i32 = &mut my_speed;
395 /// To get a pointer to a boxed value, dereference the box:
398 /// let my_num: Box<i32> = Box::new(10);
399 /// let my_num_ptr: *const i32 = &*my_num;
400 /// let mut my_speed: Box<i32> = Box::new(88);
401 /// let my_speed_ptr: *mut i32 = &mut *my_speed;
404 /// This does not take ownership of the original allocation
405 /// and requires no resource management later,
406 /// but you must not use the pointer after its lifetime.
408 /// ## 2. Consume a box (`Box<T>`).
410 /// The [`into_raw`] function consumes a box and returns
411 /// the raw pointer. It doesn't destroy `T` or deallocate any memory.
414 /// let my_speed: Box<i32> = Box::new(88);
415 /// let my_speed: *mut i32 = Box::into_raw(my_speed);
417 /// // By taking ownership of the original `Box<T>` though
418 /// // we are obligated to put it together later to be destroyed.
420 /// drop(Box::from_raw(my_speed));
424 /// Note that here the call to [`drop`] is for clarity - it indicates
425 /// that we are done with the given value and it should be destroyed.
427 /// ## 3. Get it from C.
430 /// # #![feature(libc)]
431 /// extern crate libc;
437 /// let my_num: *mut i32 = libc::malloc(mem::size_of::<i32>()) as *mut i32;
438 /// if my_num.is_null() {
439 /// panic!("failed to allocate memory");
441 /// libc::free(my_num as *mut libc::c_void);
446 /// Usually you wouldn't literally use `malloc` and `free` from Rust,
447 /// but C APIs hand out a lot of pointers generally, so are a common source
448 /// of raw pointers in Rust.
450 /// [`null`]: ../std/ptr/fn.null.html
451 /// [`null_mut`]: ../std/ptr/fn.null_mut.html
452 /// [`is_null`]: ../std/primitive.pointer.html#method.is_null
453 /// [`offset`]: ../std/primitive.pointer.html#method.offset
454 /// [`into_raw`]: ../std/boxed/struct.Box.html#method.into_raw
455 /// [`drop`]: ../std/mem/fn.drop.html
456 #[stable(feature = "rust1", since = "1.0.0")]
459 #[doc(primitive = "array")]
461 /// A fixed-size array, denoted `[T; N]`, for the element type, `T`, and the
462 /// non-negative compile-time constant size, `N`.
464 /// There are two syntactic forms for creating an array:
466 /// * A list with each element, i.e. `[x, y, z]`.
467 /// * A repeat expression `[x; N]`, which produces an array with `N` copies of `x`.
468 /// The type of `x` must be [`Copy`][copy].
470 /// Arrays of sizes from 0 to 32 (inclusive) implement the following traits if
471 /// the element type allows it:
473 /// - [`Debug`][debug]
474 /// - [`IntoIterator`][intoiterator] (implemented for `&[T; N]` and `&mut [T; N]`)
475 /// - [`PartialEq`][partialeq], [`PartialOrd`][partialord], [`Eq`][eq], [`Ord`][ord]
477 /// - [`AsRef`][asref], [`AsMut`][asmut]
478 /// - [`Borrow`][borrow], [`BorrowMut`][borrowmut]
479 /// - [`Default`][default]
481 /// This limitation on the size `N` exists because Rust does not yet support
482 /// code that is generic over the size of an array type. `[Foo; 3]` and `[Bar; 3]`
483 /// are instances of same generic type `[T; 3]`, but `[Foo; 3]` and `[Foo; 5]` are
484 /// entirely different types. As a stopgap, trait implementations are
485 /// statically generated up to size 32.
487 /// Arrays of *any* size are [`Copy`][copy] if the element type is [`Copy`][copy]
488 /// and [`Clone`][clone] if the element type is [`Clone`][clone]. This works
489 /// because [`Copy`][copy] and [`Clone`][clone] traits are specially known
492 /// Arrays coerce to [slices (`[T]`)][slice], so a slice method may be called on
493 /// an array. Indeed, this provides most of the API for working with arrays.
494 /// Slices have a dynamic size and do not coerce to arrays.
496 /// There is no way to move elements out of an array. See [`mem::replace`][replace]
497 /// for an alternative.
502 /// let mut array: [i32; 3] = [0; 3];
507 /// assert_eq!([1, 2], &array[1..]);
509 /// // This loop prints: 0 1 2
510 /// for x in &array {
511 /// print!("{} ", x);
515 /// An array itself is not iterable:
517 /// ```compile_fail,E0277
518 /// let array: [i32; 3] = [0; 3];
520 /// for x in array { }
521 /// // error: the trait bound `[i32; 3]: std::iter::Iterator` is not satisfied
524 /// The solution is to coerce the array to a slice by calling a slice method:
527 /// # let array: [i32; 3] = [0; 3];
528 /// for x in array.iter() { }
531 /// If the array has 32 or fewer elements (see above), you can also use the
532 /// array reference's [`IntoIterator`] implementation:
535 /// # let array: [i32; 3] = [0; 3];
536 /// for x in &array { }
539 /// [slice]: primitive.slice.html
540 /// [copy]: marker/trait.Copy.html
541 /// [clone]: clone/trait.Clone.html
542 /// [debug]: fmt/trait.Debug.html
543 /// [intoiterator]: iter/trait.IntoIterator.html
544 /// [partialeq]: cmp/trait.PartialEq.html
545 /// [partialord]: cmp/trait.PartialOrd.html
546 /// [eq]: cmp/trait.Eq.html
547 /// [ord]: cmp/trait.Ord.html
548 /// [hash]: hash/trait.Hash.html
549 /// [asref]: convert/trait.AsRef.html
550 /// [asmut]: convert/trait.AsMut.html
551 /// [borrow]: borrow/trait.Borrow.html
552 /// [borrowmut]: borrow/trait.BorrowMut.html
553 /// [default]: default/trait.Default.html
554 /// [replace]: mem/fn.replace.html
555 /// [`IntoIterator`]: iter/trait.IntoIterator.html
557 #[stable(feature = "rust1", since = "1.0.0")]
560 #[doc(primitive = "slice")]
565 /// A dynamically-sized view into a contiguous sequence, `[T]`.
567 /// *[See also the `std::slice` module](slice/index.html).*
569 /// Slices are a view into a block of memory represented as a pointer and a
574 /// let vec = vec![1, 2, 3];
575 /// let int_slice = &vec[..];
576 /// // coercing an array to a slice
577 /// let str_slice: &[&str] = &["one", "two", "three"];
580 /// Slices are either mutable or shared. The shared slice type is `&[T]`,
581 /// while the mutable slice type is `&mut [T]`, where `T` represents the element
582 /// type. For example, you can mutate the block of memory that a mutable slice
586 /// let x = &mut [1, 2, 3];
588 /// assert_eq!(x, &[1, 7, 3]);
591 #[stable(feature = "rust1", since = "1.0.0")]
594 #[doc(primitive = "str")]
598 /// *[See also the `std::str` module](str/index.html).*
600 /// The `str` type, also called a 'string slice', is the most primitive string
601 /// type. It is usually seen in its borrowed form, `&str`. It is also the type
602 /// of string literals, `&'static str`.
604 /// String slices are always valid UTF-8.
608 /// String literals are string slices:
611 /// let hello = "Hello, world!";
613 /// // with an explicit type annotation
614 /// let hello: &'static str = "Hello, world!";
617 /// They are `'static` because they're stored directly in the final binary, and
618 /// so will be valid for the `'static` duration.
622 /// A `&str` is made up of two components: a pointer to some bytes, and a
623 /// length. You can look at these with the [`as_ptr`] and [`len`] methods:
629 /// let story = "Once upon a time...";
631 /// let ptr = story.as_ptr();
632 /// let len = story.len();
634 /// // story has nineteen bytes
635 /// assert_eq!(19, len);
637 /// // We can re-build a str out of ptr and len. This is all unsafe because
638 /// // we are responsible for making sure the two components are valid:
640 /// // First, we build a &[u8]...
641 /// let slice = slice::from_raw_parts(ptr, len);
643 /// // ... and then convert that slice into a string slice
644 /// str::from_utf8(slice)
647 /// assert_eq!(s, Ok(story));
650 /// [`as_ptr`]: #method.as_ptr
651 /// [`len`]: #method.len
653 /// Note: This example shows the internals of `&str`. `unsafe` should not be
654 /// used to get a string slice under normal circumstances. Use `as_slice`
656 #[stable(feature = "rust1", since = "1.0.0")]
659 #[doc(primitive = "tuple")]
664 /// A finite heterogeneous sequence, `(T, U, ..)`.
666 /// Let's cover each of those in turn:
668 /// Tuples are *finite*. In other words, a tuple has a length. Here's a tuple
672 /// ("hello", 5, 'c');
675 /// 'Length' is also sometimes called 'arity' here; each tuple of a different
676 /// length is a different, distinct type.
678 /// Tuples are *heterogeneous*. This means that each element of the tuple can
679 /// have a different type. In that tuple above, it has the type:
683 /// (&'static str, i32, char)
684 /// # = ("hello", 5, 'c');
687 /// Tuples are a *sequence*. This means that they can be accessed by position;
688 /// this is called 'tuple indexing', and it looks like this:
691 /// let tuple = ("hello", 5, 'c');
693 /// assert_eq!(tuple.0, "hello");
694 /// assert_eq!(tuple.1, 5);
695 /// assert_eq!(tuple.2, 'c');
698 /// For more about tuples, see [the book](../book/first-edition/primitive-types.html#tuples).
700 /// # Trait implementations
702 /// If every type inside a tuple implements one of the following traits, then a
703 /// tuple itself also implements it.
715 /// [`Clone`]: clone/trait.Clone.html
716 /// [`Copy`]: marker/trait.Copy.html
717 /// [`PartialEq`]: cmp/trait.PartialEq.html
718 /// [`Eq`]: cmp/trait.Eq.html
719 /// [`PartialOrd`]: cmp/trait.PartialOrd.html
720 /// [`Ord`]: cmp/trait.Ord.html
721 /// [`Debug`]: fmt/trait.Debug.html
722 /// [`Default`]: default/trait.Default.html
723 /// [`Hash`]: hash/trait.Hash.html
725 /// Due to a temporary restriction in Rust's type system, these traits are only
726 /// implemented on tuples of arity 12 or less. In the future, this may change.
733 /// let tuple = ("hello", 5, 'c');
735 /// assert_eq!(tuple.0, "hello");
738 /// Tuples are often used as a return type when you want to return more than
742 /// fn calculate_point() -> (i32, i32) {
743 /// // Don't do a calculation, that's not the point of the example
747 /// let point = calculate_point();
749 /// assert_eq!(point.0, 4);
750 /// assert_eq!(point.1, 5);
752 /// // Combining this with patterns can be nicer.
754 /// let (x, y) = calculate_point();
756 /// assert_eq!(x, 4);
757 /// assert_eq!(y, 5);
760 #[stable(feature = "rust1", since = "1.0.0")]
763 #[doc(primitive = "f32")]
764 /// The 32-bit floating point type.
766 /// *[See also the `std::f32` module](f32/index.html).*
768 #[stable(feature = "rust1", since = "1.0.0")]
771 #[doc(primitive = "f64")]
773 /// The 64-bit floating point type.
775 /// *[See also the `std::f64` module](f64/index.html).*
777 #[stable(feature = "rust1", since = "1.0.0")]
780 #[doc(primitive = "i8")]
782 /// The 8-bit signed integer type.
784 /// *[See also the `std::i8` module](i8/index.html).*
785 #[stable(feature = "rust1", since = "1.0.0")]
788 #[doc(primitive = "i16")]
790 /// The 16-bit signed integer type.
792 /// *[See also the `std::i16` module](i16/index.html).*
793 #[stable(feature = "rust1", since = "1.0.0")]
796 #[doc(primitive = "i32")]
798 /// The 32-bit signed integer type.
800 /// *[See also the `std::i32` module](i32/index.html).*
801 #[stable(feature = "rust1", since = "1.0.0")]
804 #[doc(primitive = "i64")]
806 /// The 64-bit signed integer type.
808 /// *[See also the `std::i64` module](i64/index.html).*
809 #[stable(feature = "rust1", since = "1.0.0")]
812 #[doc(primitive = "i128")]
814 /// The 128-bit signed integer type.
816 /// *[See also the `std::i128` module](i128/index.html).*
817 #[stable(feature = "i128", since="1.26.0")]
820 #[doc(primitive = "u8")]
822 /// The 8-bit unsigned integer type.
824 /// *[See also the `std::u8` module](u8/index.html).*
825 #[stable(feature = "rust1", since = "1.0.0")]
828 #[doc(primitive = "u16")]
830 /// The 16-bit unsigned integer type.
832 /// *[See also the `std::u16` module](u16/index.html).*
833 #[stable(feature = "rust1", since = "1.0.0")]
836 #[doc(primitive = "u32")]
838 /// The 32-bit unsigned integer type.
840 /// *[See also the `std::u32` module](u32/index.html).*
841 #[stable(feature = "rust1", since = "1.0.0")]
844 #[doc(primitive = "u64")]
846 /// The 64-bit unsigned integer type.
848 /// *[See also the `std::u64` module](u64/index.html).*
849 #[stable(feature = "rust1", since = "1.0.0")]
852 #[doc(primitive = "u128")]
854 /// The 128-bit unsigned integer type.
856 /// *[See also the `std::u128` module](u128/index.html).*
857 #[stable(feature = "i128", since="1.26.0")]
860 #[doc(primitive = "isize")]
862 /// The pointer-sized signed integer type.
864 /// *[See also the `std::isize` module](isize/index.html).*
866 /// The size of this primitive is how many bytes it takes to reference any
867 /// location in memory. For example, on a 32 bit target, this is 4 bytes
868 /// and on a 64 bit target, this is 8 bytes.
869 #[stable(feature = "rust1", since = "1.0.0")]
872 #[doc(primitive = "usize")]
874 /// The pointer-sized unsigned integer type.
876 /// *[See also the `std::usize` module](usize/index.html).*
878 /// The size of this primitive is how many bytes it takes to reference any
879 /// location in memory. For example, on a 32 bit target, this is 4 bytes
880 /// and on a 64 bit target, this is 8 bytes.
881 #[stable(feature = "rust1", since = "1.0.0")]
884 #[doc(primitive = "reference")]
887 /// References, both shared and mutable.
889 /// A reference represents a borrow of some owned value. You can get one by using the `&` or `&mut`
890 /// operators on a value, or by using a `ref` or `ref mut` pattern.
892 /// For those familiar with pointers, a reference is just a pointer that is assumed to not be null.
893 /// In fact, `Option<&T>` has the same memory representation as a nullable pointer, and can be
894 /// passed across FFI boundaries as such.
896 /// In most cases, references can be used much like the original value. Field access, method
897 /// calling, and indexing work the same (save for mutability rules, of course). In addition, the
898 /// comparison operators transparently defer to the referent's implementation, allowing references
899 /// to be compared the same as owned values.
901 /// References have a lifetime attached to them, which represents the scope for which the borrow is
902 /// valid. A lifetime is said to "outlive" another one if its representative scope is as long or
903 /// longer than the other. The `'static` lifetime is the longest lifetime, which represents the
904 /// total life of the program. For example, string literals have a `'static` lifetime because the
905 /// text data is embedded into the binary of the program, rather than in an allocation that needs
906 /// to be dynamically managed.
908 /// `&mut T` references can be freely coerced into `&T` references with the same referent type, and
909 /// references with longer lifetimes can be freely coerced into references with shorter ones.
911 /// Reference equality by address, instead of comparing the values pointed to, is accomplished via
912 /// implicit reference-pointer coercion and raw pointer equality via [`ptr::eq`], while
913 /// [`PartialEq`] compares values.
915 /// [`ptr::eq`]: ptr/fn.eq.html
916 /// [`PartialEq`]: cmp/trait.PartialEq.html
922 /// let other_five = 5;
923 /// let five_ref = &five;
924 /// let same_five_ref = &five;
925 /// let other_five_ref = &other_five;
927 /// assert!(five_ref == same_five_ref);
928 /// assert!(five_ref == other_five_ref);
930 /// assert!(ptr::eq(five_ref, same_five_ref));
931 /// assert!(!ptr::eq(five_ref, other_five_ref));
934 /// For more information on how to use references, see [the book's section on "References and
935 /// Borrowing"][book-refs].
937 /// [book-refs]: ../book/second-edition/ch04-02-references-and-borrowing.html
939 /// # Trait implementations
941 /// The following traits are implemented for all `&T`, regardless of the type of its referent:
944 /// * [`Clone`] \(Note that this will not defer to `T`'s `Clone` implementation if it exists!)
949 /// [`Copy`]: marker/trait.Copy.html
950 /// [`Clone`]: clone/trait.Clone.html
951 /// [`Deref`]: ops/trait.Deref.html
952 /// [`Borrow`]: borrow/trait.Borrow.html
953 /// [`Pointer`]: fmt/trait.Pointer.html
955 /// `&mut T` references get all of the above except `Copy` and `Clone` (to prevent creating
956 /// multiple simultaneous mutable borrows), plus the following, regardless of the type of its
962 /// [`DerefMut`]: ops/trait.DerefMut.html
963 /// [`BorrowMut`]: borrow/trait.BorrowMut.html
965 /// The following traits are implemented on `&T` references if the underlying `T` also implements
968 /// * All the traits in [`std::fmt`] except [`Pointer`] and [`fmt::Write`]
974 /// * [`Fn`] \(in addition, `&T` references get [`FnMut`] and [`FnOnce`] if `T: Fn`)
976 /// * [`ToSocketAddrs`]
978 /// [`std::fmt`]: fmt/index.html
979 /// [`fmt::Write`]: fmt/trait.Write.html
980 /// [`PartialOrd`]: cmp/trait.PartialOrd.html
981 /// [`Ord`]: cmp/trait.Ord.html
982 /// [`PartialEq`]: cmp/trait.PartialEq.html
983 /// [`Eq`]: cmp/trait.Eq.html
984 /// [`AsRef`]: convert/trait.AsRef.html
985 /// [`Fn`]: ops/trait.Fn.html
986 /// [`FnMut`]: ops/trait.FnMut.html
987 /// [`FnOnce`]: ops/trait.FnOnce.html
988 /// [`Hash`]: hash/trait.Hash.html
989 /// [`ToSocketAddrs`]: net/trait.ToSocketAddrs.html
991 /// `&mut T` references get all of the above except `ToSocketAddrs`, plus the following, if `T`
992 /// implements that trait:
995 /// * [`FnMut`] \(in addition, `&mut T` references get [`FnOnce`] if `T: FnMut`)
998 /// * [`DoubleEndedIterator`]
999 /// * [`ExactSizeIterator`]
1000 /// * [`FusedIterator`]
1001 /// * [`TrustedLen`]
1002 /// * [`Send`] \(note that `&T` references only get `Send` if `T: Sync`)
1008 /// [`AsMut`]: convert/trait.AsMut.html
1009 /// [`Iterator`]: iter/trait.Iterator.html
1010 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1011 /// [`ExactSizeIterator`]: iter/trait.ExactSizeIterator.html
1012 /// [`FusedIterator`]: iter/trait.FusedIterator.html
1013 /// [`TrustedLen`]: iter/trait.TrustedLen.html
1014 /// [`Send`]: marker/trait.Send.html
1015 /// [`io::Write`]: io/trait.Write.html
1016 /// [`Read`]: io/trait.Read.html
1017 /// [`Seek`]: io/trait.Seek.html
1018 /// [`BufRead`]: io/trait.BufRead.html
1020 /// Note that due to method call deref coercion, simply calling a trait method will act like they
1021 /// work on references as well as they do on owned values! The implementations described here are
1022 /// meant for generic contexts, where the final type `T` is a type parameter or otherwise not
1024 #[stable(feature = "rust1", since = "1.0.0")]
1027 #[doc(primitive = "fn")]
1029 /// Function pointers, like `fn(usize) -> bool`.
1031 /// *See also the traits [`Fn`], [`FnMut`], and [`FnOnce`].*
1033 /// [`Fn`]: ops/trait.Fn.html
1034 /// [`FnMut`]: ops/trait.FnMut.html
1035 /// [`FnOnce`]: ops/trait.FnOnce.html
1037 /// Plain function pointers are obtained by casting either plain functions, or closures that don't
1038 /// capture an environment:
1041 /// fn add_one(x: usize) -> usize {
1045 /// let ptr: fn(usize) -> usize = add_one;
1046 /// assert_eq!(ptr(5), 6);
1048 /// let clos: fn(usize) -> usize = |x| x + 5;
1049 /// assert_eq!(clos(5), 10);
1052 /// In addition to varying based on their signature, function pointers come in two flavors: safe
1053 /// and unsafe. Plain `fn()` function pointers can only point to safe functions,
1054 /// while `unsafe fn()` function pointers can point to safe or unsafe functions.
1057 /// fn add_one(x: usize) -> usize {
1061 /// unsafe fn add_one_unsafely(x: usize) -> usize {
1065 /// let safe_ptr: fn(usize) -> usize = add_one;
1067 /// //ERROR: mismatched types: expected normal fn, found unsafe fn
1068 /// //let bad_ptr: fn(usize) -> usize = add_one_unsafely;
1070 /// let unsafe_ptr: unsafe fn(usize) -> usize = add_one_unsafely;
1071 /// let really_safe_ptr: unsafe fn(usize) -> usize = add_one;
1074 /// On top of that, function pointers can vary based on what ABI they use. This is achieved by
1075 /// adding the `extern` keyword to the type name, followed by the ABI in question. For example,
1076 /// `fn()` is different from `extern "C" fn()`, which itself is different from `extern "stdcall"
1077 /// fn()`, and so on for the various ABIs that Rust supports. Non-`extern` functions have an ABI
1078 /// of `"Rust"`, and `extern` functions without an explicit ABI have an ABI of `"C"`. For more
1079 /// information, see [the nomicon's section on foreign calling conventions][nomicon-abi].
1081 /// [nomicon-abi]: ../nomicon/ffi.html#foreign-calling-conventions
1083 /// Extern function declarations with the "C" or "cdecl" ABIs can also be *variadic*, allowing them
1084 /// to be called with a variable number of arguments. Normal rust functions, even those with an
1085 /// `extern "ABI"`, cannot be variadic. For more information, see [the nomicon's section on
1086 /// variadic functions][nomicon-variadic].
1088 /// [nomicon-variadic]: ../nomicon/ffi.html#variadic-functions
1090 /// These markers can be combined, so `unsafe extern "stdcall" fn()` is a valid type.
1092 /// Like references in rust, function pointers are assumed to not be null, so if you want to pass a
1093 /// function pointer over FFI and be able to accommodate null pointers, make your type
1094 /// `Option<fn()>` with your required signature.
1096 /// Function pointers implement the following traits:
1101 /// * [`PartialOrd`]
1107 /// [`Clone`]: clone/trait.Clone.html
1108 /// [`PartialEq`]: cmp/trait.PartialEq.html
1109 /// [`Eq`]: cmp/trait.Eq.html
1110 /// [`PartialOrd`]: cmp/trait.PartialOrd.html
1111 /// [`Ord`]: cmp/trait.Ord.html
1112 /// [`Hash`]: hash/trait.Hash.html
1113 /// [`Pointer`]: fmt/trait.Pointer.html
1114 /// [`Debug`]: fmt/trait.Debug.html
1116 /// Due to a temporary restriction in Rust's type system, these traits are only implemented on
1117 /// functions that take 12 arguments or less, with the `"Rust"` and `"C"` ABIs. In the future, this
1120 /// In addition, function pointers of *any* signature, ABI, or safety are [`Copy`], and all *safe*
1121 /// function pointers implement [`Fn`], [`FnMut`], and [`FnOnce`]. This works because these traits
1122 /// are specially known to the compiler.
1124 /// [`Copy`]: marker/trait.Copy.html
1125 #[stable(feature = "rust1", since = "1.0.0")]