1 #[doc(primitive = "bool")]
3 #[doc(alias = "false")]
7 /// The `bool` represents a value, which could only be either `true` or `false`. If you cast
8 /// a `bool` into an integer, `true` will be 1 and `false` will be 0.
12 /// `bool` implements various traits, such as [`BitAnd`], [`BitOr`], [`Not`], etc.,
13 /// which allow us to perform boolean operations using `&`, `|` and `!`.
15 /// `if` always demands a `bool` value. [`assert!`], being an important macro in testing,
16 /// checks whether an expression returns `true`.
19 /// let bool_val = true & false | false;
20 /// assert!(!bool_val);
23 /// [`assert!`]: macro.assert.html
24 /// [`BitAnd`]: ops/trait.BitAnd.html
25 /// [`BitOr`]: ops/trait.BitOr.html
26 /// [`Not`]: ops/trait.Not.html
30 /// A trivial example of the usage of `bool`,
33 /// let praise_the_borrow_checker = true;
35 /// // using the `if` conditional
36 /// if praise_the_borrow_checker {
37 /// println!("oh, yeah!");
39 /// println!("what?!!");
42 /// // ... or, a match pattern
43 /// match praise_the_borrow_checker {
44 /// true => println!("keep praising!"),
45 /// false => println!("you should praise!"),
49 /// Also, since `bool` implements the [`Copy`](marker/trait.Copy.html) trait, we don't
50 /// have to worry about the move semantics (just like the integer and float primitives).
52 /// Now an example of `bool` cast to integer type:
55 /// assert_eq!(true as i32, 1);
56 /// assert_eq!(false as i32, 0);
58 #[stable(feature = "rust1", since = "1.0.0")]
61 #[doc(primitive = "never")]
64 /// The `!` type, also called "never".
66 /// `!` represents the type of computations which never resolve to any value at all. For example,
67 /// the [`exit`] function `fn exit(code: i32) -> !` exits the process without ever returning, and
70 /// `break`, `continue` and `return` expressions also have type `!`. For example we are allowed to
74 /// # fn foo() -> u32 {
81 /// Although the `let` is pointless here, it illustrates the meaning of `!`. Since `x` is never
82 /// assigned a value (because `return` returns from the entire function), `x` can be given type
83 /// `!`. We could also replace `return 123` with a `panic!` or a never-ending `loop` and this code
84 /// would still be valid.
86 /// A more realistic usage of `!` is in this code:
89 /// # fn get_a_number() -> Option<u32> { None }
91 /// let num: u32 = match get_a_number() {
98 /// Both match arms must produce values of type [`u32`], but since `break` never produces a value
99 /// at all we know it can never produce a value which isn't a [`u32`]. This illustrates another
100 /// behaviour of the `!` type - expressions with type `!` will coerce into any other type.
102 /// [`u32`]: primitive.str.html
103 /// [`exit`]: process/fn.exit.html
105 /// # `!` and generics
107 /// ## Infallible errors
109 /// The main place you'll see `!` used explicitly is in generic code. Consider the [`FromStr`]
113 /// trait FromStr: Sized {
115 /// fn from_str(s: &str) -> Result<Self, Self::Err>;
119 /// When implementing this trait for [`String`] we need to pick a type for [`Err`]. And since
120 /// converting a string into a string will never result in an error, the appropriate type is `!`.
121 /// (Currently the type actually used is an enum with no variants, though this is only because `!`
122 /// was added to Rust at a later date and it may change in the future.) With an [`Err`] type of
123 /// `!`, if we have to call [`String::from_str`] for some reason the result will be a
124 /// [`Result<String, !>`] which we can unpack like this:
126 /// ```ignore (string-from-str-error-type-is-not-never-yet)
127 /// #[feature(exhaustive_patterns)]
128 /// // NOTE: this does not work today!
129 /// let Ok(s) = String::from_str("hello");
132 /// Since the [`Err`] variant contains a `!`, it can never occur. If the `exhaustive_patterns`
133 /// feature is present this means we can exhaustively match on [`Result<T, !>`] by just taking the
134 /// [`Ok`] variant. This illustrates another behaviour of `!` - it can be used to "delete" certain
135 /// enum variants from generic types like `Result`.
137 /// ## Infinite loops
139 /// While [`Result<T, !>`] is very useful for removing errors, `!` can also be used to remove
140 /// successes as well. If we think of [`Result<T, !>`] as "if this function returns, it has not
141 /// errored," we get a very intuitive idea of [`Result<!, E>`] as well: if the function returns, it
144 /// For example, consider the case of a simple web server, which can be simplified to:
146 /// ```ignore (hypothetical-example)
148 /// let (client, request) = get_request().expect("disconnected");
149 /// let response = request.process();
150 /// response.send(client);
154 /// Currently, this isn't ideal, because we simply panic whenever we fail to get a new connection.
155 /// Instead, we'd like to keep track of this error, like this:
157 /// ```ignore (hypothetical-example)
159 /// match get_request() {
160 /// Err(err) => break err,
161 /// Ok((client, request)) => {
162 /// let response = request.process();
163 /// response.send(client);
169 /// Now, when the server disconnects, we exit the loop with an error instead of panicking. While it
170 /// might be intuitive to simply return the error, we might want to wrap it in a [`Result<!, E>`]
173 /// ```ignore (hypothetical-example)
174 /// fn server_loop() -> Result<!, ConnectionError> {
176 /// let (client, request) = get_request()?;
177 /// let response = request.process();
178 /// response.send(client);
183 /// Now, we can use `?` instead of `match`, and the return type makes a lot more sense: if the loop
184 /// ever stops, it means that an error occurred. We don't even have to wrap the loop in an `Ok`
185 /// because `!` coerces to `Result<!, ConnectionError>` automatically.
187 /// [`String::from_str`]: str/trait.FromStr.html#tymethod.from_str
188 /// [`Result<String, !>`]: result/enum.Result.html
189 /// [`Result<T, !>`]: result/enum.Result.html
190 /// [`Result<!, E>`]: result/enum.Result.html
191 /// [`Ok`]: result/enum.Result.html#variant.Ok
192 /// [`String`]: string/struct.String.html
193 /// [`Err`]: result/enum.Result.html#variant.Err
194 /// [`FromStr`]: str/trait.FromStr.html
198 /// When writing your own traits, `!` should have an `impl` whenever there is an obvious `impl`
199 /// which doesn't `panic!`. As it turns out, most traits can have an `impl` for `!`. Take [`Debug`]
205 /// # fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result;
207 /// impl Debug for ! {
208 /// fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
214 /// Once again we're using `!`'s ability to coerce into any other type, in this case
215 /// [`fmt::Result`]. Since this method takes a `&!` as an argument we know that it can never be
216 /// called (because there is no value of type `!` for it to be called with). Writing `*self`
217 /// essentially tells the compiler "We know that this code can never be run, so just treat the
218 /// entire function body as having type [`fmt::Result`]". This pattern can be used a lot when
219 /// implementing traits for `!`. Generally, any trait which only has methods which take a `self`
220 /// parameter should have such an impl.
222 /// On the other hand, one trait which would not be appropriate to implement is [`Default`]:
226 /// fn default() -> Self;
230 /// Since `!` has no values, it has no default value either. It's true that we could write an
231 /// `impl` for this which simply panics, but the same is true for any type (we could `impl
232 /// Default` for (eg.) [`File`] by just making [`default()`] panic.)
234 /// [`fmt::Result`]: fmt/type.Result.html
235 /// [`File`]: fs/struct.File.html
236 /// [`Debug`]: fmt/trait.Debug.html
237 /// [`Default`]: default/trait.Default.html
238 /// [`default()`]: default/trait.Default.html#tymethod.default
240 #[stable(feature = "never_type", since = "1.41.0")]
243 #[doc(primitive = "char")]
245 /// A character type.
247 /// The `char` type represents a single character. More specifically, since
248 /// 'character' isn't a well-defined concept in Unicode, `char` is a '[Unicode
249 /// scalar value]', which is similar to, but not the same as, a '[Unicode code
252 /// [Unicode scalar value]: http://www.unicode.org/glossary/#unicode_scalar_value
253 /// [Unicode code point]: http://www.unicode.org/glossary/#code_point
255 /// This documentation describes a number of methods and trait implementations on the
256 /// `char` type. For technical reasons, there is additional, separate
257 /// documentation in [the `std::char` module](char/index.html) as well.
261 /// `char` is always four bytes in size. This is a different representation than
262 /// a given character would have as part of a [`String`]. For example:
265 /// let v = vec!['h', 'e', 'l', 'l', 'o'];
267 /// // five elements times four bytes for each element
268 /// assert_eq!(20, v.len() * std::mem::size_of::<char>());
270 /// let s = String::from("hello");
272 /// // five elements times one byte per element
273 /// assert_eq!(5, s.len() * std::mem::size_of::<u8>());
276 /// [`String`]: string/struct.String.html
278 /// As always, remember that a human intuition for 'character' may not map to
279 /// Unicode's definitions. For example, despite looking similar, the 'é'
280 /// character is one Unicode code point while 'é' is two Unicode code points:
283 /// let mut chars = "é".chars();
284 /// // U+00e9: 'latin small letter e with acute'
285 /// assert_eq!(Some('\u{00e9}'), chars.next());
286 /// assert_eq!(None, chars.next());
288 /// let mut chars = "é".chars();
289 /// // U+0065: 'latin small letter e'
290 /// assert_eq!(Some('\u{0065}'), chars.next());
291 /// // U+0301: 'combining acute accent'
292 /// assert_eq!(Some('\u{0301}'), chars.next());
293 /// assert_eq!(None, chars.next());
296 /// This means that the contents of the first string above _will_ fit into a
297 /// `char` while the contents of the second string _will not_. Trying to create
298 /// a `char` literal with the contents of the second string gives an error:
301 /// error: character literal may only contain one codepoint: 'é'
306 /// Another implication of the 4-byte fixed size of a `char` is that
307 /// per-`char` processing can end up using a lot more memory:
310 /// let s = String::from("love: ❤️");
311 /// let v: Vec<char> = s.chars().collect();
313 /// assert_eq!(12, std::mem::size_of_val(&s[..]));
314 /// assert_eq!(32, std::mem::size_of_val(&v[..]));
316 #[stable(feature = "rust1", since = "1.0.0")]
319 #[doc(primitive = "unit")]
321 /// The `()` type, sometimes called "unit" or "nil".
323 /// The `()` type has exactly one value `()`, and is used when there
324 /// is no other meaningful value that could be returned. `()` is most
325 /// commonly seen implicitly: functions without a `-> ...` implicitly
326 /// have return type `()`, that is, these are equivalent:
329 /// fn long() -> () {}
334 /// The semicolon `;` can be used to discard the result of an
335 /// expression at the end of a block, making the expression (and thus
336 /// the block) evaluate to `()`. For example,
339 /// fn returns_i64() -> i64 {
342 /// fn returns_unit() {
354 #[stable(feature = "rust1", since = "1.0.0")]
357 #[doc(primitive = "pointer")]
359 /// Raw, unsafe pointers, `*const T`, and `*mut T`.
361 /// *[See also the `std::ptr` module](ptr/index.html).*
363 /// Working with raw pointers in Rust is uncommon, typically limited to a few patterns.
364 /// Raw pointers can be unaligned or [`null`]. However, when a raw pointer is
365 /// dereferenced (using the `*` operator), it must be non-null and aligned.
367 /// Storing through a raw pointer using `*ptr = data` calls `drop` on the old value, so
368 /// [`write`] must be used if the type has drop glue and memory is not already
369 /// initialized - otherwise `drop` would be called on the uninitialized memory.
371 /// Use the [`null`] and [`null_mut`] functions to create null pointers, and the
372 /// [`is_null`] method of the `*const T` and `*mut T` types to check for null.
373 /// The `*const T` and `*mut T` types also define the [`offset`] method, for
376 /// # Common ways to create raw pointers
378 /// ## 1. Coerce a reference (`&T`) or mutable reference (`&mut T`).
381 /// let my_num: i32 = 10;
382 /// let my_num_ptr: *const i32 = &my_num;
383 /// let mut my_speed: i32 = 88;
384 /// let my_speed_ptr: *mut i32 = &mut my_speed;
387 /// To get a pointer to a boxed value, dereference the box:
390 /// let my_num: Box<i32> = Box::new(10);
391 /// let my_num_ptr: *const i32 = &*my_num;
392 /// let mut my_speed: Box<i32> = Box::new(88);
393 /// let my_speed_ptr: *mut i32 = &mut *my_speed;
396 /// This does not take ownership of the original allocation
397 /// and requires no resource management later,
398 /// but you must not use the pointer after its lifetime.
400 /// ## 2. Consume a box (`Box<T>`).
402 /// The [`into_raw`] function consumes a box and returns
403 /// the raw pointer. It doesn't destroy `T` or deallocate any memory.
406 /// let my_speed: Box<i32> = Box::new(88);
407 /// let my_speed: *mut i32 = Box::into_raw(my_speed);
409 /// // By taking ownership of the original `Box<T>` though
410 /// // we are obligated to put it together later to be destroyed.
412 /// drop(Box::from_raw(my_speed));
416 /// Note that here the call to [`drop`] is for clarity - it indicates
417 /// that we are done with the given value and it should be destroyed.
419 /// ## 3. Get it from C.
422 /// # #![feature(rustc_private)]
423 /// extern crate libc;
428 /// let my_num: *mut i32 = libc::malloc(mem::size_of::<i32>()) as *mut i32;
429 /// if my_num.is_null() {
430 /// panic!("failed to allocate memory");
432 /// libc::free(my_num as *mut libc::c_void);
436 /// Usually you wouldn't literally use `malloc` and `free` from Rust,
437 /// but C APIs hand out a lot of pointers generally, so are a common source
438 /// of raw pointers in Rust.
440 /// [`null`]: ../std/ptr/fn.null.html
441 /// [`null_mut`]: ../std/ptr/fn.null_mut.html
442 /// [`is_null`]: ../std/primitive.pointer.html#method.is_null
443 /// [`offset`]: ../std/primitive.pointer.html#method.offset
444 /// [`into_raw`]: ../std/boxed/struct.Box.html#method.into_raw
445 /// [`drop`]: ../std/mem/fn.drop.html
446 /// [`write`]: ../std/ptr/fn.write.html
447 #[stable(feature = "rust1", since = "1.0.0")]
450 #[doc(primitive = "array")]
452 /// A fixed-size array, denoted `[T; N]`, for the element type, `T`, and the
453 /// non-negative compile-time constant size, `N`.
455 /// There are two syntactic forms for creating an array:
457 /// * A list with each element, i.e., `[x, y, z]`.
458 /// * A repeat expression `[x; N]`, which produces an array with `N` copies of `x`.
459 /// The type of `x` must be [`Copy`][copy].
461 /// Arrays of sizes from 0 to 32 (inclusive) implement the following traits if
462 /// the element type allows it:
464 /// - [`Debug`][debug]
465 /// - [`IntoIterator`][intoiterator] (implemented for `&[T; N]` and `&mut [T; N]`)
466 /// - [`PartialEq`][partialeq], [`PartialOrd`][partialord], [`Eq`][eq], [`Ord`][ord]
468 /// - [`AsRef`][asref], [`AsMut`][asmut]
469 /// - [`Borrow`][borrow], [`BorrowMut`][borrowmut]
470 /// - [`Default`][default]
472 /// This limitation on the size `N` exists because Rust does not yet support
473 /// code that is generic over the size of an array type. `[Foo; 3]` and `[Bar; 3]`
474 /// are instances of same generic type `[T; 3]`, but `[Foo; 3]` and `[Foo; 5]` are
475 /// entirely different types. As a stopgap, trait implementations are
476 /// statically generated up to size 32.
478 /// Arrays of *any* size are [`Copy`][copy] if the element type is [`Copy`][copy]
479 /// and [`Clone`][clone] if the element type is [`Clone`][clone]. This works
480 /// because [`Copy`][copy] and [`Clone`][clone] traits are specially known
483 /// Arrays coerce to [slices (`[T]`)][slice], so a slice method may be called on
484 /// an array. Indeed, this provides most of the API for working with arrays.
485 /// Slices have a dynamic size and do not coerce to arrays.
487 /// You can move elements out of an array with a slice pattern. If you want
488 /// one element, see [`mem::replace`][replace].
493 /// let mut array: [i32; 3] = [0; 3];
498 /// assert_eq!([1, 2], &array[1..]);
500 /// // This loop prints: 0 1 2
501 /// for x in &array {
502 /// print!("{} ", x);
506 /// An array itself is not iterable:
508 /// ```compile_fail,E0277
509 /// let array: [i32; 3] = [0; 3];
511 /// for x in array { }
512 /// // error: the trait bound `[i32; 3]: std::iter::Iterator` is not satisfied
515 /// The solution is to coerce the array to a slice by calling a slice method:
518 /// # let array: [i32; 3] = [0; 3];
519 /// for x in array.iter() { }
522 /// If the array has 32 or fewer elements (see above), you can also use the
523 /// array reference's [`IntoIterator`] implementation:
526 /// # let array: [i32; 3] = [0; 3];
527 /// for x in &array { }
530 /// You can use a slice pattern to move elements out of an array:
533 /// fn move_away(_: String) { /* Do interesting things. */ }
535 /// let [john, roa] = ["John".to_string(), "Roa".to_string()];
540 /// [slice]: primitive.slice.html
541 /// [copy]: marker/trait.Copy.html
542 /// [clone]: clone/trait.Clone.html
543 /// [debug]: fmt/trait.Debug.html
544 /// [intoiterator]: iter/trait.IntoIterator.html
545 /// [partialeq]: cmp/trait.PartialEq.html
546 /// [partialord]: cmp/trait.PartialOrd.html
547 /// [eq]: cmp/trait.Eq.html
548 /// [ord]: cmp/trait.Ord.html
549 /// [hash]: hash/trait.Hash.html
550 /// [asref]: convert/trait.AsRef.html
551 /// [asmut]: convert/trait.AsMut.html
552 /// [borrow]: borrow/trait.Borrow.html
553 /// [borrowmut]: borrow/trait.BorrowMut.html
554 /// [default]: default/trait.Default.html
555 /// [replace]: mem/fn.replace.html
556 /// [`IntoIterator`]: iter/trait.IntoIterator.html
558 #[stable(feature = "rust1", since = "1.0.0")]
561 #[doc(primitive = "slice")]
565 /// A dynamically-sized view into a contiguous sequence, `[T]`. Contiguous here
566 /// means that elements are laid out so that every element is the same
567 /// distance from its neighbors.
569 /// *[See also the `std::slice` module](slice/index.html).*
571 /// Slices are a view into a block of memory represented as a pointer and a
576 /// let vec = vec![1, 2, 3];
577 /// let int_slice = &vec[..];
578 /// // coercing an array to a slice
579 /// let str_slice: &[&str] = &["one", "two", "three"];
582 /// Slices are either mutable or shared. The shared slice type is `&[T]`,
583 /// while the mutable slice type is `&mut [T]`, where `T` represents the element
584 /// type. For example, you can mutate the block of memory that a mutable slice
588 /// let mut x = [1, 2, 3];
589 /// let x = &mut x[..]; // Take a full slice of `x`.
591 /// assert_eq!(x, &[1, 7, 3]);
593 #[stable(feature = "rust1", since = "1.0.0")]
596 #[doc(primitive = "str")]
600 /// *[See also the `std::str` module](str/index.html).*
602 /// The `str` type, also called a 'string slice', is the most primitive string
603 /// type. It is usually seen in its borrowed form, `&str`. It is also the type
604 /// of string literals, `&'static str`.
606 /// String slices are always valid UTF-8.
610 /// String literals are string slices:
613 /// let hello = "Hello, world!";
615 /// // with an explicit type annotation
616 /// let hello: &'static str = "Hello, world!";
619 /// They are `'static` because they're stored directly in the final binary, and
620 /// so will be valid for the `'static` duration.
624 /// A `&str` is made up of two components: a pointer to some bytes, and a
625 /// length. You can look at these with the [`as_ptr`] and [`len`] methods:
631 /// let story = "Once upon a time...";
633 /// let ptr = story.as_ptr();
634 /// let len = story.len();
636 /// // story has nineteen bytes
637 /// assert_eq!(19, len);
639 /// // We can re-build a str out of ptr and len. This is all unsafe because
640 /// // we are responsible for making sure the two components are valid:
642 /// // First, we build a &[u8]...
643 /// let slice = slice::from_raw_parts(ptr, len);
645 /// // ... and then convert that slice into a string slice
646 /// str::from_utf8(slice)
649 /// assert_eq!(s, Ok(story));
652 /// [`as_ptr`]: #method.as_ptr
653 /// [`len`]: #method.len
655 /// Note: This example shows the internals of `&str`. `unsafe` should not be
656 /// used to get a string slice under normal circumstances. Use `as_str`
658 #[stable(feature = "rust1", since = "1.0.0")]
661 #[doc(primitive = "tuple")]
666 /// A finite heterogeneous sequence, `(T, U, ..)`.
668 /// Let's cover each of those in turn:
670 /// Tuples are *finite*. In other words, a tuple has a length. Here's a tuple
674 /// ("hello", 5, 'c');
677 /// 'Length' is also sometimes called 'arity' here; each tuple of a different
678 /// length is a different, distinct type.
680 /// Tuples are *heterogeneous*. This means that each element of the tuple can
681 /// have a different type. In that tuple above, it has the type:
685 /// (&'static str, i32, char)
686 /// # = ("hello", 5, 'c');
689 /// Tuples are a *sequence*. This means that they can be accessed by position;
690 /// this is called 'tuple indexing', and it looks like this:
693 /// let tuple = ("hello", 5, 'c');
695 /// assert_eq!(tuple.0, "hello");
696 /// assert_eq!(tuple.1, 5);
697 /// assert_eq!(tuple.2, 'c');
700 /// The sequential nature of the tuple applies to its implementations of various
701 /// traits. For example, in `PartialOrd` and `Ord`, the elements are compared
702 /// sequentially until the first non-equal set is found.
704 /// For more about tuples, see [the book](../book/ch03-02-data-types.html#the-tuple-type).
706 /// # Trait implementations
708 /// If every type inside a tuple implements one of the following traits, then a
709 /// tuple itself also implements it.
721 /// [`Clone`]: clone/trait.Clone.html
722 /// [`Copy`]: marker/trait.Copy.html
723 /// [`PartialEq`]: cmp/trait.PartialEq.html
724 /// [`Eq`]: cmp/trait.Eq.html
725 /// [`PartialOrd`]: cmp/trait.PartialOrd.html
726 /// [`Ord`]: cmp/trait.Ord.html
727 /// [`Debug`]: fmt/trait.Debug.html
728 /// [`Default`]: default/trait.Default.html
729 /// [`Hash`]: hash/trait.Hash.html
731 /// Due to a temporary restriction in Rust's type system, these traits are only
732 /// implemented on tuples of arity 12 or less. In the future, this may change.
739 /// let tuple = ("hello", 5, 'c');
741 /// assert_eq!(tuple.0, "hello");
744 /// Tuples are often used as a return type when you want to return more than
748 /// fn calculate_point() -> (i32, i32) {
749 /// // Don't do a calculation, that's not the point of the example
753 /// let point = calculate_point();
755 /// assert_eq!(point.0, 4);
756 /// assert_eq!(point.1, 5);
758 /// // Combining this with patterns can be nicer.
760 /// let (x, y) = calculate_point();
762 /// assert_eq!(x, 4);
763 /// assert_eq!(y, 5);
766 #[stable(feature = "rust1", since = "1.0.0")]
769 #[doc(primitive = "f32")]
770 /// The 32-bit floating point type.
772 /// *[See also the `std::f32` module](f32/index.html).*
774 #[stable(feature = "rust1", since = "1.0.0")]
777 #[doc(primitive = "f64")]
779 /// The 64-bit floating point type.
781 /// *[See also the `std::f64` module](f64/index.html).*
783 #[stable(feature = "rust1", since = "1.0.0")]
786 #[doc(primitive = "i8")]
788 /// The 8-bit signed integer type.
790 /// *[See also the `std::i8` module](i8/index.html).*
791 #[stable(feature = "rust1", since = "1.0.0")]
794 #[doc(primitive = "i16")]
796 /// The 16-bit signed integer type.
798 /// *[See also the `std::i16` module](i16/index.html).*
799 #[stable(feature = "rust1", since = "1.0.0")]
802 #[doc(primitive = "i32")]
804 /// The 32-bit signed integer type.
806 /// *[See also the `std::i32` module](i32/index.html).*
807 #[stable(feature = "rust1", since = "1.0.0")]
810 #[doc(primitive = "i64")]
812 /// The 64-bit signed integer type.
814 /// *[See also the `std::i64` module](i64/index.html).*
815 #[stable(feature = "rust1", since = "1.0.0")]
818 #[doc(primitive = "i128")]
820 /// The 128-bit signed integer type.
822 /// *[See also the `std::i128` module](i128/index.html).*
823 #[stable(feature = "i128", since="1.26.0")]
826 #[doc(primitive = "u8")]
828 /// The 8-bit unsigned integer type.
830 /// *[See also the `std::u8` module](u8/index.html).*
831 #[stable(feature = "rust1", since = "1.0.0")]
834 #[doc(primitive = "u16")]
836 /// The 16-bit unsigned integer type.
838 /// *[See also the `std::u16` module](u16/index.html).*
839 #[stable(feature = "rust1", since = "1.0.0")]
842 #[doc(primitive = "u32")]
844 /// The 32-bit unsigned integer type.
846 /// *[See also the `std::u32` module](u32/index.html).*
847 #[stable(feature = "rust1", since = "1.0.0")]
850 #[doc(primitive = "u64")]
852 /// The 64-bit unsigned integer type.
854 /// *[See also the `std::u64` module](u64/index.html).*
855 #[stable(feature = "rust1", since = "1.0.0")]
858 #[doc(primitive = "u128")]
860 /// The 128-bit unsigned integer type.
862 /// *[See also the `std::u128` module](u128/index.html).*
863 #[stable(feature = "i128", since="1.26.0")]
866 #[doc(primitive = "isize")]
868 /// The pointer-sized signed integer type.
870 /// *[See also the `std::isize` module](isize/index.html).*
872 /// The size of this primitive is how many bytes it takes to reference any
873 /// location in memory. For example, on a 32 bit target, this is 4 bytes
874 /// and on a 64 bit target, this is 8 bytes.
875 #[stable(feature = "rust1", since = "1.0.0")]
878 #[doc(primitive = "usize")]
880 /// The pointer-sized unsigned integer type.
882 /// *[See also the `std::usize` module](usize/index.html).*
884 /// The size of this primitive is how many bytes it takes to reference any
885 /// location in memory. For example, on a 32 bit target, this is 4 bytes
886 /// and on a 64 bit target, this is 8 bytes.
887 #[stable(feature = "rust1", since = "1.0.0")]
890 #[doc(primitive = "reference")]
893 /// References, both shared and mutable.
895 /// A reference represents a borrow of some owned value. You can get one by using the `&` or `&mut`
896 /// operators on a value, or by using a `ref` or `ref mut` pattern.
898 /// For those familiar with pointers, a reference is just a pointer that is assumed to be
899 /// aligned, not null, and pointing to memory containing a valid value of `T` - for example,
900 /// `&bool` can only point to an allocation containing the integer values `1` (`true`) or `0`
901 /// (`false`), but creating a `&bool` that points to an allocation containing
902 /// the value `3` causes undefined behaviour.
903 /// In fact, `Option<&T>` has the same memory representation as a
904 /// nullable but aligned pointer, and can be passed across FFI boundaries as such.
906 /// In most cases, references can be used much like the original value. Field access, method
907 /// calling, and indexing work the same (save for mutability rules, of course). In addition, the
908 /// comparison operators transparently defer to the referent's implementation, allowing references
909 /// to be compared the same as owned values.
911 /// References have a lifetime attached to them, which represents the scope for which the borrow is
912 /// valid. A lifetime is said to "outlive" another one if its representative scope is as long or
913 /// longer than the other. The `'static` lifetime is the longest lifetime, which represents the
914 /// total life of the program. For example, string literals have a `'static` lifetime because the
915 /// text data is embedded into the binary of the program, rather than in an allocation that needs
916 /// to be dynamically managed.
918 /// `&mut T` references can be freely coerced into `&T` references with the same referent type, and
919 /// references with longer lifetimes can be freely coerced into references with shorter ones.
921 /// Reference equality by address, instead of comparing the values pointed to, is accomplished via
922 /// implicit reference-pointer coercion and raw pointer equality via [`ptr::eq`], while
923 /// [`PartialEq`] compares values.
925 /// [`ptr::eq`]: ptr/fn.eq.html
926 /// [`PartialEq`]: cmp/trait.PartialEq.html
932 /// let other_five = 5;
933 /// let five_ref = &five;
934 /// let same_five_ref = &five;
935 /// let other_five_ref = &other_five;
937 /// assert!(five_ref == same_five_ref);
938 /// assert!(five_ref == other_five_ref);
940 /// assert!(ptr::eq(five_ref, same_five_ref));
941 /// assert!(!ptr::eq(five_ref, other_five_ref));
944 /// For more information on how to use references, see [the book's section on "References and
945 /// Borrowing"][book-refs].
947 /// [book-refs]: ../book/ch04-02-references-and-borrowing.html
949 /// # Trait implementations
951 /// The following traits are implemented for all `&T`, regardless of the type of its referent:
954 /// * [`Clone`] \(Note that this will not defer to `T`'s `Clone` implementation if it exists!)
959 /// [`Copy`]: marker/trait.Copy.html
960 /// [`Clone`]: clone/trait.Clone.html
961 /// [`Deref`]: ops/trait.Deref.html
962 /// [`Borrow`]: borrow/trait.Borrow.html
963 /// [`Pointer`]: fmt/trait.Pointer.html
965 /// `&mut T` references get all of the above except `Copy` and `Clone` (to prevent creating
966 /// multiple simultaneous mutable borrows), plus the following, regardless of the type of its
972 /// [`DerefMut`]: ops/trait.DerefMut.html
973 /// [`BorrowMut`]: borrow/trait.BorrowMut.html
975 /// The following traits are implemented on `&T` references if the underlying `T` also implements
978 /// * All the traits in [`std::fmt`] except [`Pointer`] and [`fmt::Write`]
984 /// * [`Fn`] \(in addition, `&T` references get [`FnMut`] and [`FnOnce`] if `T: Fn`)
986 /// * [`ToSocketAddrs`]
988 /// [`std::fmt`]: fmt/index.html
989 /// [`fmt::Write`]: fmt/trait.Write.html
990 /// [`PartialOrd`]: cmp/trait.PartialOrd.html
991 /// [`Ord`]: cmp/trait.Ord.html
992 /// [`PartialEq`]: cmp/trait.PartialEq.html
993 /// [`Eq`]: cmp/trait.Eq.html
994 /// [`AsRef`]: convert/trait.AsRef.html
995 /// [`Fn`]: ops/trait.Fn.html
996 /// [`FnMut`]: ops/trait.FnMut.html
997 /// [`FnOnce`]: ops/trait.FnOnce.html
998 /// [`Hash`]: hash/trait.Hash.html
999 /// [`ToSocketAddrs`]: net/trait.ToSocketAddrs.html
1001 /// `&mut T` references get all of the above except `ToSocketAddrs`, plus the following, if `T`
1002 /// implements that trait:
1005 /// * [`FnMut`] \(in addition, `&mut T` references get [`FnOnce`] if `T: FnMut`)
1006 /// * [`fmt::Write`]
1008 /// * [`DoubleEndedIterator`]
1009 /// * [`ExactSizeIterator`]
1010 /// * [`FusedIterator`]
1011 /// * [`TrustedLen`]
1012 /// * [`Send`] \(note that `&T` references only get `Send` if `T: Sync`)
1018 /// [`AsMut`]: convert/trait.AsMut.html
1019 /// [`Iterator`]: iter/trait.Iterator.html
1020 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1021 /// [`ExactSizeIterator`]: iter/trait.ExactSizeIterator.html
1022 /// [`FusedIterator`]: iter/trait.FusedIterator.html
1023 /// [`TrustedLen`]: iter/trait.TrustedLen.html
1024 /// [`Send`]: marker/trait.Send.html
1025 /// [`io::Write`]: io/trait.Write.html
1026 /// [`Read`]: io/trait.Read.html
1027 /// [`Seek`]: io/trait.Seek.html
1028 /// [`BufRead`]: io/trait.BufRead.html
1030 /// Note that due to method call deref coercion, simply calling a trait method will act like they
1031 /// work on references as well as they do on owned values! The implementations described here are
1032 /// meant for generic contexts, where the final type `T` is a type parameter or otherwise not
1034 #[stable(feature = "rust1", since = "1.0.0")]
1037 #[doc(primitive = "fn")]
1039 /// Function pointers, like `fn(usize) -> bool`.
1041 /// *See also the traits [`Fn`], [`FnMut`], and [`FnOnce`].*
1043 /// [`Fn`]: ops/trait.Fn.html
1044 /// [`FnMut`]: ops/trait.FnMut.html
1045 /// [`FnOnce`]: ops/trait.FnOnce.html
1047 /// Function pointers are pointers that point to *code*, not data. They can be called
1048 /// just like functions. Like references, function pointers are, among other things, assumed to
1049 /// not be null, so if you want to pass a function pointer over FFI and be able to accommodate null
1050 /// pointers, make your type `Option<fn()>` with your required signature.
1052 /// Plain function pointers are obtained by casting either plain functions, or closures that don't
1053 /// capture an environment:
1056 /// fn add_one(x: usize) -> usize {
1060 /// let ptr: fn(usize) -> usize = add_one;
1061 /// assert_eq!(ptr(5), 6);
1063 /// let clos: fn(usize) -> usize = |x| x + 5;
1064 /// assert_eq!(clos(5), 10);
1067 /// In addition to varying based on their signature, function pointers come in two flavors: safe
1068 /// and unsafe. Plain `fn()` function pointers can only point to safe functions,
1069 /// while `unsafe fn()` function pointers can point to safe or unsafe functions.
1072 /// fn add_one(x: usize) -> usize {
1076 /// unsafe fn add_one_unsafely(x: usize) -> usize {
1080 /// let safe_ptr: fn(usize) -> usize = add_one;
1082 /// //ERROR: mismatched types: expected normal fn, found unsafe fn
1083 /// //let bad_ptr: fn(usize) -> usize = add_one_unsafely;
1085 /// let unsafe_ptr: unsafe fn(usize) -> usize = add_one_unsafely;
1086 /// let really_safe_ptr: unsafe fn(usize) -> usize = add_one;
1089 /// On top of that, function pointers can vary based on what ABI they use. This is achieved by
1090 /// adding the `extern` keyword to the type name, followed by the ABI in question. For example,
1091 /// `fn()` is different from `extern "C" fn()`, which itself is different from `extern "stdcall"
1092 /// fn()`, and so on for the various ABIs that Rust supports. Non-`extern` functions have an ABI
1093 /// of `"Rust"`, and `extern` functions without an explicit ABI have an ABI of `"C"`. For more
1094 /// information, see [the nomicon's section on foreign calling conventions][nomicon-abi].
1096 /// [nomicon-abi]: ../nomicon/ffi.html#foreign-calling-conventions
1098 /// Extern function declarations with the "C" or "cdecl" ABIs can also be *variadic*, allowing them
1099 /// to be called with a variable number of arguments. Normal rust functions, even those with an
1100 /// `extern "ABI"`, cannot be variadic. For more information, see [the nomicon's section on
1101 /// variadic functions][nomicon-variadic].
1103 /// [nomicon-variadic]: ../nomicon/ffi.html#variadic-functions
1105 /// These markers can be combined, so `unsafe extern "stdcall" fn()` is a valid type.
1107 /// Function pointers implement the following traits:
1112 /// * [`PartialOrd`]
1118 /// [`Clone`]: clone/trait.Clone.html
1119 /// [`PartialEq`]: cmp/trait.PartialEq.html
1120 /// [`Eq`]: cmp/trait.Eq.html
1121 /// [`PartialOrd`]: cmp/trait.PartialOrd.html
1122 /// [`Ord`]: cmp/trait.Ord.html
1123 /// [`Hash`]: hash/trait.Hash.html
1124 /// [`Pointer`]: fmt/trait.Pointer.html
1125 /// [`Debug`]: fmt/trait.Debug.html
1127 /// Due to a temporary restriction in Rust's type system, these traits are only implemented on
1128 /// functions that take 12 arguments or less, with the `"Rust"` and `"C"` ABIs. In the future, this
1131 /// In addition, function pointers of *any* signature, ABI, or safety are [`Copy`], and all *safe*
1132 /// function pointers implement [`Fn`], [`FnMut`], and [`FnOnce`]. This works because these traits
1133 /// are specially known to the compiler.
1135 /// [`Copy`]: marker/trait.Copy.html
1136 #[stable(feature = "rust1", since = "1.0.0")]