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")]
15 /// The `bool` represents a value, which could only be either `true` or `false`. If you cast
16 /// a `bool` into an integer, `true` will be 1 and `false` will be 0.
20 /// `bool` implements various traits, such as [`BitAnd`], [`BitOr`], [`Not`], etc.,
21 /// which allow us to perform boolean operations using `&`, `|` and `!`.
23 /// [`if`] always demands a `bool` value. [`assert!`], being an important macro in testing,
24 /// checks whether an expression returns `true`.
27 /// let bool_val = true & false | false;
28 /// assert!(!bool_val);
31 /// [`assert!`]: macro.assert.html
32 /// [`if`]: ../book/first-edition/if.html
33 /// [`BitAnd`]: ops/trait.BitAnd.html
34 /// [`BitOr`]: ops/trait.BitOr.html
35 /// [`Not`]: ops/trait.Not.html
39 /// A trivial example of the usage of `bool`,
42 /// let praise_the_borrow_checker = true;
44 /// // using the `if` conditional
45 /// if praise_the_borrow_checker {
46 /// println!("oh, yeah!");
48 /// println!("what?!!");
51 /// // ... or, a match pattern
52 /// match praise_the_borrow_checker {
53 /// true => println!("keep praising!"),
54 /// false => println!("you should praise!"),
58 /// Also, since `bool` implements the [`Copy`](marker/trait.Copy.html) trait, we don't
59 /// have to worry about the move semantics (just like the integer and float primitives).
61 /// Now an example of `bool` cast to integer type:
64 /// assert_eq!(true as i32, 1);
65 /// assert_eq!(false as i32, 0);
67 #[stable(feature = "rust1", since = "1.0.0")]
70 #[doc(primitive = "char")]
74 /// The `char` type represents a single character. More specifically, since
75 /// 'character' isn't a well-defined concept in Unicode, `char` is a '[Unicode
76 /// scalar value]', which is similar to, but not the same as, a '[Unicode code
79 /// [Unicode scalar value]: http://www.unicode.org/glossary/#unicode_scalar_value
80 /// [Unicode code point]: http://www.unicode.org/glossary/#code_point
82 /// This documentation describes a number of methods and trait implementations on the
83 /// `char` type. For technical reasons, there is additional, separate
84 /// documentation in [the `std::char` module](char/index.html) as well.
88 /// `char` is always four bytes in size. This is a different representation than
89 /// a given character would have as part of a [`String`]. For example:
92 /// let v = vec!['h', 'e', 'l', 'l', 'o'];
94 /// // five elements times four bytes for each element
95 /// assert_eq!(20, v.len() * std::mem::size_of::<char>());
97 /// let s = String::from("hello");
99 /// // five elements times one byte per element
100 /// assert_eq!(5, s.len() * std::mem::size_of::<u8>());
103 /// [`String`]: string/struct.String.html
105 /// As always, remember that a human intuition for 'character' may not map to
106 /// Unicode's definitions. For example, emoji symbols such as '❤️' can be more
107 /// than one Unicode code point; this ❤️ in particular is two:
110 /// let s = String::from("❤️");
112 /// // we get two chars out of a single ❤️
113 /// let mut iter = s.chars();
114 /// assert_eq!(Some('\u{2764}'), iter.next());
115 /// assert_eq!(Some('\u{fe0f}'), iter.next());
116 /// assert_eq!(None, iter.next());
119 /// This means it won't fit into a `char`. Trying to create a literal with
120 /// `let heart = '❤️';` gives an error:
123 /// error: character literal may only contain one codepoint: '❤
124 /// let heart = '❤️';
128 /// Another implication of the 4-byte fixed size of a `char` is that
129 /// per-`char` processing can end up using a lot more memory:
132 /// let s = String::from("love: ❤️");
133 /// let v: Vec<char> = s.chars().collect();
135 /// assert_eq!(12, s.len() * std::mem::size_of::<u8>());
136 /// assert_eq!(32, v.len() * std::mem::size_of::<char>());
138 #[stable(feature = "rust1", since = "1.0.0")]
141 #[doc(primitive = "unit")]
143 /// The `()` type, sometimes called "unit" or "nil".
145 /// The `()` type has exactly one value `()`, and is used when there
146 /// is no other meaningful value that could be returned. `()` is most
147 /// commonly seen implicitly: functions without a `-> ...` implicitly
148 /// have return type `()`, that is, these are equivalent:
151 /// fn long() -> () {}
156 /// The semicolon `;` can be used to discard the result of an
157 /// expression at the end of a block, making the expression (and thus
158 /// the block) evaluate to `()`. For example,
161 /// fn returns_i64() -> i64 {
164 /// fn returns_unit() {
176 #[stable(feature = "rust1", since = "1.0.0")]
179 #[doc(primitive = "pointer")]
181 /// Raw, unsafe pointers, `*const T`, and `*mut T`.
183 /// Working with raw pointers in Rust is uncommon,
184 /// typically limited to a few patterns.
186 /// Use the [`null`] function to create null pointers, and the [`is_null`] method
187 /// of the `*const T` type to check for null. The `*const T` type also defines
188 /// the [`offset`] method, for pointer math.
190 /// # Common ways to create raw pointers
192 /// ## 1. Coerce a reference (`&T`) or mutable reference (`&mut T`).
195 /// let my_num: i32 = 10;
196 /// let my_num_ptr: *const i32 = &my_num;
197 /// let mut my_speed: i32 = 88;
198 /// let my_speed_ptr: *mut i32 = &mut my_speed;
201 /// To get a pointer to a boxed value, dereference the box:
204 /// let my_num: Box<i32> = Box::new(10);
205 /// let my_num_ptr: *const i32 = &*my_num;
206 /// let mut my_speed: Box<i32> = Box::new(88);
207 /// let my_speed_ptr: *mut i32 = &mut *my_speed;
210 /// This does not take ownership of the original allocation
211 /// and requires no resource management later,
212 /// but you must not use the pointer after its lifetime.
214 /// ## 2. Consume a box (`Box<T>`).
216 /// The [`into_raw`] function consumes a box and returns
217 /// the raw pointer. It doesn't destroy `T` or deallocate any memory.
220 /// let my_speed: Box<i32> = Box::new(88);
221 /// let my_speed: *mut i32 = Box::into_raw(my_speed);
223 /// // By taking ownership of the original `Box<T>` though
224 /// // we are obligated to put it together later to be destroyed.
226 /// drop(Box::from_raw(my_speed));
230 /// Note that here the call to [`drop`] is for clarity - it indicates
231 /// that we are done with the given value and it should be destroyed.
233 /// ## 3. Get it from C.
236 /// # #![feature(libc)]
237 /// extern crate libc;
243 /// let my_num: *mut i32 = libc::malloc(mem::size_of::<i32>()) as *mut i32;
244 /// if my_num.is_null() {
245 /// panic!("failed to allocate memory");
247 /// libc::free(my_num as *mut libc::c_void);
252 /// Usually you wouldn't literally use `malloc` and `free` from Rust,
253 /// but C APIs hand out a lot of pointers generally, so are a common source
254 /// of raw pointers in Rust.
256 /// *[See also the `std::ptr` module](ptr/index.html).*
258 /// [`null`]: ../std/ptr/fn.null.html
259 /// [`is_null`]: ../std/primitive.pointer.html#method.is_null
260 /// [`offset`]: ../std/primitive.pointer.html#method.offset
261 /// [`into_raw`]: ../std/boxed/struct.Box.html#method.into_raw
262 /// [`drop`]: ../std/mem/fn.drop.html
263 #[stable(feature = "rust1", since = "1.0.0")]
266 #[doc(primitive = "array")]
268 /// A fixed-size array, denoted `[T; N]`, for the element type, `T`, and the
269 /// non-negative compile-time constant size, `N`.
271 /// There are two syntactic forms for creating an array:
273 /// * A list with each element, i.e. `[x, y, z]`.
274 /// * A repeat expression `[x; N]`, which produces an array with `N` copies of `x`.
275 /// The type of `x` must be [`Copy`][copy].
277 /// Arrays of sizes from 0 to 32 (inclusive) implement the following traits if
278 /// the element type allows it:
280 /// - [`Clone`][clone] (only if `T: [Copy][copy]`)
281 /// - [`Debug`][debug]
282 /// - [`IntoIterator`][intoiterator] (implemented for `&[T; N]` and `&mut [T; N]`)
283 /// - [`PartialEq`][partialeq], [`PartialOrd`][partialord], [`Eq`][eq], [`Ord`][ord]
285 /// - [`AsRef`][asref], [`AsMut`][asmut]
286 /// - [`Borrow`][borrow], [`BorrowMut`][borrowmut]
287 /// - [`Default`][default]
289 /// This limitation on the size `N` exists because Rust does not yet support
290 /// code that is generic over the size of an array type. `[Foo; 3]` and `[Bar; 3]`
291 /// are instances of same generic type `[T; 3]`, but `[Foo; 3]` and `[Foo; 5]` are
292 /// entirely different types. As a stopgap, trait implementations are
293 /// statically generated up to size 32.
295 /// Arrays of *any* size are [`Copy`][copy] if the element type is [`Copy`][copy]. This
296 /// works because the [`Copy`][copy] trait is specially known to the compiler.
298 /// Arrays coerce to [slices (`[T]`)][slice], so a slice method may be called on
299 /// an array. Indeed, this provides most of the API for working with arrays.
300 /// Slices have a dynamic size and do not coerce to arrays.
302 /// There is no way to move elements out of an array. See [`mem::replace`][replace]
303 /// for an alternative.
308 /// let mut array: [i32; 3] = [0; 3];
313 /// assert_eq!([1, 2], &array[1..]);
315 /// // This loop prints: 0 1 2
316 /// for x in &array {
317 /// print!("{} ", x);
321 /// An array itself is not iterable:
324 /// let array: [i32; 3] = [0; 3];
326 /// for x in array { }
327 /// // error: the trait bound `[i32; 3]: std::iter::Iterator` is not satisfied
330 /// The solution is to coerce the array to a slice by calling a slice method:
333 /// # let array: [i32; 3] = [0; 3];
334 /// for x in array.iter() { }
337 /// If the array has 32 or fewer elements (see above), you can also use the
338 /// array reference's [`IntoIterator`] implementation:
341 /// # let array: [i32; 3] = [0; 3];
342 /// for x in &array { }
345 /// [slice]: primitive.slice.html
346 /// [copy]: marker/trait.Copy.html
347 /// [clone]: clone/trait.Clone.html
348 /// [debug]: fmt/trait.Debug.html
349 /// [intoiterator]: iter/trait.IntoIterator.html
350 /// [partialeq]: cmp/trait.PartialEq.html
351 /// [partialord]: cmp/trait.PartialOrd.html
352 /// [eq]: cmp/trait.Eq.html
353 /// [ord]: cmp/trait.Ord.html
354 /// [hash]: hash/trait.Hash.html
355 /// [asref]: convert/trait.AsRef.html
356 /// [asmut]: convert/trait.AsMut.html
357 /// [borrow]: borrow/trait.Borrow.html
358 /// [borrowmut]: borrow/trait.BorrowMut.html
359 /// [default]: default/trait.Default.html
360 /// [replace]: mem/fn.replace.html
361 /// [`IntoIterator`]: iter/trait.IntoIterator.html
363 #[stable(feature = "rust1", since = "1.0.0")]
366 #[doc(primitive = "slice")]
368 /// A dynamically-sized view into a contiguous sequence, `[T]`.
370 /// Slices are a view into a block of memory represented as a pointer and a
375 /// let vec = vec![1, 2, 3];
376 /// let int_slice = &vec[..];
377 /// // coercing an array to a slice
378 /// let str_slice: &[&str] = &["one", "two", "three"];
381 /// Slices are either mutable or shared. The shared slice type is `&[T]`,
382 /// while the mutable slice type is `&mut [T]`, where `T` represents the element
383 /// type. For example, you can mutate the block of memory that a mutable slice
387 /// let x = &mut [1, 2, 3];
389 /// assert_eq!(x, &[1, 7, 3]);
392 /// *[See also the `std::slice` module](slice/index.html).*
394 #[stable(feature = "rust1", since = "1.0.0")]
397 #[doc(primitive = "str")]
401 /// The `str` type, also called a 'string slice', is the most primitive string
402 /// type. It is usually seen in its borrowed form, `&str`. It is also the type
403 /// of string literals, `&'static str`.
405 /// Strings slices are always valid UTF-8.
407 /// This documentation describes a number of methods and trait implementations
408 /// on the `str` type. For technical reasons, there is additional, separate
409 /// documentation in [the `std::str` module](str/index.html) as well.
413 /// String literals are string slices:
416 /// let hello = "Hello, world!";
418 /// // with an explicit type annotation
419 /// let hello: &'static str = "Hello, world!";
422 /// They are `'static` because they're stored directly in the final binary, and
423 /// so will be valid for the `'static` duration.
427 /// A `&str` is made up of two components: a pointer to some bytes, and a
428 /// length. You can look at these with the [`.as_ptr`] and [`len`] methods:
434 /// let story = "Once upon a time...";
436 /// let ptr = story.as_ptr();
437 /// let len = story.len();
439 /// // story has nineteen bytes
440 /// assert_eq!(19, len);
442 /// // We can re-build a str out of ptr and len. This is all unsafe because
443 /// // we are responsible for making sure the two components are valid:
445 /// // First, we build a &[u8]...
446 /// let slice = slice::from_raw_parts(ptr, len);
448 /// // ... and then convert that slice into a string slice
449 /// str::from_utf8(slice)
452 /// assert_eq!(s, Ok(story));
455 /// [`.as_ptr`]: #method.as_ptr
456 /// [`len`]: #method.len
458 /// Note: This example shows the internals of `&str`. `unsafe` should not be
459 /// used to get a string slice under normal circumstances. Use `.as_slice()`
461 #[stable(feature = "rust1", since = "1.0.0")]
464 #[doc(primitive = "tuple")]
466 /// A finite heterogeneous sequence, `(T, U, ..)`.
468 /// Let's cover each of those in turn:
470 /// Tuples are *finite*. In other words, a tuple has a length. Here's a tuple
474 /// ("hello", 5, 'c');
477 /// 'Length' is also sometimes called 'arity' here; each tuple of a different
478 /// length is a different, distinct type.
480 /// Tuples are *heterogeneous*. This means that each element of the tuple can
481 /// have a different type. In that tuple above, it has the type:
484 /// (&'static str, i32, char)
487 /// Tuples are a *sequence*. This means that they can be accessed by position;
488 /// this is called 'tuple indexing', and it looks like this:
491 /// let tuple = ("hello", 5, 'c');
493 /// assert_eq!(tuple.0, "hello");
494 /// assert_eq!(tuple.1, 5);
495 /// assert_eq!(tuple.2, 'c');
498 /// For more about tuples, see [the book](../book/first-edition/primitive-types.html#tuples).
500 /// # Trait implementations
502 /// If every type inside a tuple implements one of the following traits, then a
503 /// tuple itself also implements it.
515 /// [`Clone`]: clone/trait.Clone.html
516 /// [`Copy`]: marker/trait.Copy.html
517 /// [`PartialEq`]: cmp/trait.PartialEq.html
518 /// [`Eq`]: cmp/trait.Eq.html
519 /// [`PartialOrd`]: cmp/trait.PartialOrd.html
520 /// [`Ord`]: cmp/trait.Ord.html
521 /// [`Debug`]: fmt/trait.Debug.html
522 /// [`Default`]: default/trait.Default.html
523 /// [`Hash`]: hash/trait.Hash.html
525 /// Due to a temporary restriction in Rust's type system, these traits are only
526 /// implemented on tuples of arity 12 or less. In the future, this may change.
533 /// let tuple = ("hello", 5, 'c');
535 /// assert_eq!(tuple.0, "hello");
538 /// Tuples are often used as a return type when you want to return more than
542 /// fn calculate_point() -> (i32, i32) {
543 /// // Don't do a calculation, that's not the point of the example
547 /// let point = calculate_point();
549 /// assert_eq!(point.0, 4);
550 /// assert_eq!(point.1, 5);
552 /// // Combining this with patterns can be nicer.
554 /// let (x, y) = calculate_point();
556 /// assert_eq!(x, 4);
557 /// assert_eq!(y, 5);
560 #[stable(feature = "rust1", since = "1.0.0")]
563 #[doc(primitive = "f32")]
564 /// The 32-bit floating point type.
566 /// *[See also the `std::f32` module](f32/index.html).*
568 #[stable(feature = "rust1", since = "1.0.0")]
571 #[doc(primitive = "f64")]
573 /// The 64-bit floating point type.
575 /// *[See also the `std::f64` module](f64/index.html).*
577 #[stable(feature = "rust1", since = "1.0.0")]
580 #[doc(primitive = "i8")]
582 /// The 8-bit signed integer type.
584 /// *[See also the `std::i8` module](i8/index.html).*
586 /// However, please note that examples are shared between primitive integer
587 /// types. So it's normal if you see usage of types like `i64` in there.
589 #[stable(feature = "rust1", since = "1.0.0")]
592 #[doc(primitive = "i16")]
594 /// The 16-bit signed integer type.
596 /// *[See also the `std::i16` module](i16/index.html).*
598 /// However, please note that examples are shared between primitive integer
599 /// types. So it's normal if you see usage of types like `i32` in there.
601 #[stable(feature = "rust1", since = "1.0.0")]
604 #[doc(primitive = "i32")]
606 /// The 32-bit signed integer type.
608 /// *[See also the `std::i32` module](i32/index.html).*
610 /// However, please note that examples are shared between primitive integer
611 /// types. So it's normal if you see usage of types like `i16` in there.
613 #[stable(feature = "rust1", since = "1.0.0")]
616 #[doc(primitive = "i64")]
618 /// The 64-bit signed integer type.
620 /// *[See also the `std::i64` module](i64/index.html).*
622 /// However, please note that examples are shared between primitive integer
623 /// types. So it's normal if you see usage of types like `i8` in there.
625 #[stable(feature = "rust1", since = "1.0.0")]
628 #[doc(primitive = "i128")]
630 /// The 128-bit signed integer type.
632 /// *[See also the `std::i128` module](i128/index.html).*
634 /// However, please note that examples are shared between primitive integer
635 /// types. So it's normal if you see usage of types like `i8` in there.
637 #[unstable(feature = "i128", issue="35118")]
640 #[doc(primitive = "u8")]
642 /// The 8-bit unsigned integer type.
644 /// *[See also the `std::u8` module](u8/index.html).*
646 /// However, please note that examples are shared between primitive integer
647 /// types. So it's normal if you see usage of types like `u64` in there.
649 #[stable(feature = "rust1", since = "1.0.0")]
652 #[doc(primitive = "u16")]
654 /// The 16-bit unsigned integer type.
656 /// *[See also the `std::u16` module](u16/index.html).*
658 /// However, please note that examples are shared between primitive integer
659 /// types. So it's normal if you see usage of types like `u32` in there.
661 #[stable(feature = "rust1", since = "1.0.0")]
664 #[doc(primitive = "u32")]
666 /// The 32-bit unsigned integer type.
668 /// *[See also the `std::u32` module](u32/index.html).*
670 /// However, please note that examples are shared between primitive integer
671 /// types. So it's normal if you see usage of types like `u16` in there.
673 #[stable(feature = "rust1", since = "1.0.0")]
676 #[doc(primitive = "u64")]
678 /// The 64-bit unsigned integer type.
680 /// *[See also the `std::u64` module](u64/index.html).*
682 /// However, please note that examples are shared between primitive integer
683 /// types. So it's normal if you see usage of types like `u8` in there.
685 #[stable(feature = "rust1", since = "1.0.0")]
688 #[doc(primitive = "u128")]
690 /// The 128-bit unsigned integer type.
692 /// *[See also the `std::u128` module](u128/index.html).*
694 /// However, please note that examples are shared between primitive integer
695 /// types. So it's normal if you see usage of types like `u8` in there.
697 #[unstable(feature = "i128", issue="35118")]
700 #[doc(primitive = "isize")]
702 /// The pointer-sized signed integer type.
704 /// *[See also the `std::isize` module](isize/index.html).*
706 /// However, please note that examples are shared between primitive integer
707 /// types. So it's normal if you see usage of types like `usize` in there.
709 #[stable(feature = "rust1", since = "1.0.0")]
712 #[doc(primitive = "usize")]
714 /// The pointer-sized unsigned integer type.
716 /// *[See also the `std::usize` module](usize/index.html).*
718 /// However, please note that examples are shared between primitive integer
719 /// types. So it's normal if you see usage of types like `isize` in there.
721 #[stable(feature = "rust1", since = "1.0.0")]