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/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 #[stable(feature = "rust1", since = "1.0.0")]
261 #[doc(primitive = "array")]
263 /// A fixed-size array, denoted `[T; N]`, for the element type, `T`, and the
264 /// non-negative compile-time constant size, `N`.
266 /// There are two syntactic forms for creating an array:
268 /// * A list with each element, i.e. `[x, y, z]`.
269 /// * A repeat expression `[x; N]`, which produces an array with `N` copies of `x`.
270 /// The type of `x` must be [`Copy`][copy].
272 /// Arrays of sizes from 0 to 32 (inclusive) implement the following traits if
273 /// the element type allows it:
275 /// - [`Clone`][clone] (only if `T: [Copy][copy]`)
276 /// - [`Debug`][debug]
277 /// - [`IntoIterator`][intoiterator] (implemented for `&[T; N]` and `&mut [T; N]`)
278 /// - [`PartialEq`][partialeq], [`PartialOrd`][partialord], [`Eq`][eq], [`Ord`][ord]
280 /// - [`AsRef`][asref], [`AsMut`][asmut]
281 /// - [`Borrow`][borrow], [`BorrowMut`][borrowmut]
282 /// - [`Default`][default]
284 /// This limitation on the size `N` exists because Rust does not yet support
285 /// code that is generic over the size of an array type. `[Foo; 3]` and `[Bar; 3]`
286 /// are instances of same generic type `[T; 3]`, but `[Foo; 3]` and `[Foo; 5]` are
287 /// entirely different types. As a stopgap, trait implementations are
288 /// statically generated up to size 32.
290 /// Arrays of *any* size are [`Copy`][copy] if the element type is [`Copy`][copy]. This
291 /// works because the [`Copy`][copy] trait is specially known to the compiler.
293 /// Arrays coerce to [slices (`[T]`)][slice], so a slice method may be called on
294 /// an array. Indeed, this provides most of the API for working with arrays.
295 /// Slices have a dynamic size and do not coerce to arrays.
297 /// There is no way to move elements out of an array. See [`mem::replace`][replace]
298 /// for an alternative.
303 /// let mut array: [i32; 3] = [0; 3];
308 /// assert_eq!([1, 2], &array[1..]);
310 /// // This loop prints: 0 1 2
311 /// for x in &array {
312 /// print!("{} ", x);
316 /// An array itself is not iterable:
319 /// let array: [i32; 3] = [0; 3];
321 /// for x in array { }
322 /// // error: the trait bound `[i32; 3]: std::iter::Iterator` is not satisfied
325 /// The solution is to coerce the array to a slice by calling a slice method:
328 /// # let array: [i32; 3] = [0; 3];
329 /// for x in array.iter() { }
332 /// If the array has 32 or fewer elements (see above), you can also use the
333 /// array reference's [`IntoIterator`] implementation:
336 /// # let array: [i32; 3] = [0; 3];
337 /// for x in &array { }
340 /// [slice]: primitive.slice.html
341 /// [copy]: marker/trait.Copy.html
342 /// [clone]: clone/trait.Clone.html
343 /// [debug]: fmt/trait.Debug.html
344 /// [intoiterator]: iter/trait.IntoIterator.html
345 /// [partialeq]: cmp/trait.PartialEq.html
346 /// [partialord]: cmp/trait.PartialOrd.html
347 /// [eq]: cmp/trait.Eq.html
348 /// [ord]: cmp/trait.Ord.html
349 /// [hash]: hash/trait.Hash.html
350 /// [asref]: convert/trait.AsRef.html
351 /// [asmut]: convert/trait.AsMut.html
352 /// [borrow]: borrow/trait.Borrow.html
353 /// [borrowmut]: borrow/trait.BorrowMut.html
354 /// [default]: default/trait.Default.html
355 /// [replace]: mem/fn.replace.html
356 /// [`IntoIterator`]: iter/trait.IntoIterator.html
358 #[stable(feature = "rust1", since = "1.0.0")]
361 #[doc(primitive = "slice")]
363 /// A dynamically-sized view into a contiguous sequence, `[T]`.
365 /// Slices are a view into a block of memory represented as a pointer and a
370 /// let vec = vec![1, 2, 3];
371 /// let int_slice = &vec[..];
372 /// // coercing an array to a slice
373 /// let str_slice: &[&str] = &["one", "two", "three"];
376 /// Slices are either mutable or shared. The shared slice type is `&[T]`,
377 /// while the mutable slice type is `&mut [T]`, where `T` represents the element
378 /// type. For example, you can mutate the block of memory that a mutable slice
382 /// let x = &mut [1, 2, 3];
384 /// assert_eq!(x, &[1, 7, 3]);
387 /// *[See also the `std::slice` module](slice/index.html).*
389 #[stable(feature = "rust1", since = "1.0.0")]
392 #[doc(primitive = "str")]
396 /// The `str` type, also called a 'string slice', is the most primitive string
397 /// type. It is usually seen in its borrowed form, `&str`. It is also the type
398 /// of string literals, `&'static str`.
400 /// Strings slices are always valid UTF-8.
402 /// This documentation describes a number of methods and trait implementations
403 /// on the `str` type. For technical reasons, there is additional, separate
404 /// documentation in [the `std::str` module](str/index.html) as well.
408 /// String literals are string slices:
411 /// let hello = "Hello, world!";
413 /// // with an explicit type annotation
414 /// let hello: &'static str = "Hello, world!";
417 /// They are `'static` because they're stored directly in the final binary, and
418 /// so will be valid for the `'static` duration.
422 /// A `&str` is made up of two components: a pointer to some bytes, and a
423 /// length. You can look at these with the [`.as_ptr`] and [`len`] methods:
429 /// let story = "Once upon a time...";
431 /// let ptr = story.as_ptr();
432 /// let len = story.len();
434 /// // story has nineteen bytes
435 /// assert_eq!(19, len);
437 /// // We can re-build a str out of ptr and len. This is all unsafe because
438 /// // we are responsible for making sure the two components are valid:
440 /// // First, we build a &[u8]...
441 /// let slice = slice::from_raw_parts(ptr, len);
443 /// // ... and then convert that slice into a string slice
444 /// str::from_utf8(slice)
447 /// assert_eq!(s, Ok(story));
450 /// [`.as_ptr`]: #method.as_ptr
451 /// [`len`]: #method.len
453 /// Note: This example shows the internals of `&str`. `unsafe` should not be
454 /// used to get a string slice under normal circumstances. Use `.as_slice()`
456 #[stable(feature = "rust1", since = "1.0.0")]
459 #[doc(primitive = "tuple")]
461 /// A finite heterogeneous sequence, `(T, U, ..)`.
463 /// Let's cover each of those in turn:
465 /// Tuples are *finite*. In other words, a tuple has a length. Here's a tuple
469 /// ("hello", 5, 'c');
472 /// 'Length' is also sometimes called 'arity' here; each tuple of a different
473 /// length is a different, distinct type.
475 /// Tuples are *heterogeneous*. This means that each element of the tuple can
476 /// have a different type. In that tuple above, it has the type:
479 /// (&'static str, i32, char)
482 /// Tuples are a *sequence*. This means that they can be accessed by position;
483 /// this is called 'tuple indexing', and it looks like this:
486 /// let tuple = ("hello", 5, 'c');
488 /// assert_eq!(tuple.0, "hello");
489 /// assert_eq!(tuple.1, 5);
490 /// assert_eq!(tuple.2, 'c');
493 /// For more about tuples, see [the book](../book/primitive-types.html#tuples).
495 /// # Trait implementations
497 /// If every type inside a tuple implements one of the following traits, then a
498 /// tuple itself also implements it.
510 /// [`Clone`]: clone/trait.Clone.html
511 /// [`Copy`]: marker/trait.Copy.html
512 /// [`PartialEq`]: cmp/trait.PartialEq.html
513 /// [`Eq`]: cmp/trait.Eq.html
514 /// [`PartialOrd`]: cmp/trait.PartialOrd.html
515 /// [`Ord`]: cmp/trait.Ord.html
516 /// [`Debug`]: fmt/trait.Debug.html
517 /// [`Default`]: default/trait.Default.html
518 /// [`Hash`]: hash/trait.Hash.html
520 /// Due to a temporary restriction in Rust's type system, these traits are only
521 /// implemented on tuples of arity 12 or less. In the future, this may change.
528 /// let tuple = ("hello", 5, 'c');
530 /// assert_eq!(tuple.0, "hello");
533 /// Tuples are often used as a return type when you want to return more than
537 /// fn calculate_point() -> (i32, i32) {
538 /// // Don't do a calculation, that's not the point of the example
542 /// let point = calculate_point();
544 /// assert_eq!(point.0, 4);
545 /// assert_eq!(point.1, 5);
547 /// // Combining this with patterns can be nicer.
549 /// let (x, y) = calculate_point();
551 /// assert_eq!(x, 4);
552 /// assert_eq!(y, 5);
555 #[stable(feature = "rust1", since = "1.0.0")]
558 #[doc(primitive = "f32")]
559 /// The 32-bit floating point type.
561 /// *[See also the `std::f32` module](f32/index.html).*
563 #[stable(feature = "rust1", since = "1.0.0")]
566 #[doc(primitive = "f64")]
568 /// The 64-bit floating point type.
570 /// *[See also the `std::f64` module](f64/index.html).*
572 #[stable(feature = "rust1", since = "1.0.0")]
575 #[doc(primitive = "i8")]
577 /// The 8-bit signed integer type.
579 /// *[See also the `std::i8` module](i8/index.html).*
581 /// However, please note that examples are shared between primitive integer
582 /// types. So it's normal if you see usage of types like `i64` in there.
584 #[stable(feature = "rust1", since = "1.0.0")]
587 #[doc(primitive = "i16")]
589 /// The 16-bit signed integer type.
591 /// *[See also the `std::i16` module](i16/index.html).*
593 /// However, please note that examples are shared between primitive integer
594 /// types. So it's normal if you see usage of types like `i32` in there.
596 #[stable(feature = "rust1", since = "1.0.0")]
599 #[doc(primitive = "i32")]
601 /// The 32-bit signed integer type.
603 /// *[See also the `std::i32` module](i32/index.html).*
605 /// However, please note that examples are shared between primitive integer
606 /// types. So it's normal if you see usage of types like `i16` in there.
608 #[stable(feature = "rust1", since = "1.0.0")]
611 #[doc(primitive = "i64")]
613 /// The 64-bit signed integer type.
615 /// *[See also the `std::i64` module](i64/index.html).*
617 /// However, please note that examples are shared between primitive integer
618 /// types. So it's normal if you see usage of types like `i8` in there.
620 #[stable(feature = "rust1", since = "1.0.0")]
623 #[doc(primitive = "i128")]
625 /// The 128-bit signed integer type.
627 /// *[See also the `std::i128` module](i128/index.html).*
629 /// However, please note that examples are shared between primitive integer
630 /// types. So it's normal if you see usage of types like `i8` in there.
632 #[unstable(feature = "i128", issue="35118")]
635 #[doc(primitive = "u8")]
637 /// The 8-bit unsigned integer type.
639 /// *[See also the `std::u8` module](u8/index.html).*
641 /// However, please note that examples are shared between primitive integer
642 /// types. So it's normal if you see usage of types like `u64` in there.
644 #[stable(feature = "rust1", since = "1.0.0")]
647 #[doc(primitive = "u16")]
649 /// The 16-bit unsigned integer type.
651 /// *[See also the `std::u16` module](u16/index.html).*
653 /// However, please note that examples are shared between primitive integer
654 /// types. So it's normal if you see usage of types like `u32` in there.
656 #[stable(feature = "rust1", since = "1.0.0")]
659 #[doc(primitive = "u32")]
661 /// The 32-bit unsigned integer type.
663 /// *[See also the `std::u32` module](u32/index.html).*
665 /// However, please note that examples are shared between primitive integer
666 /// types. So it's normal if you see usage of types like `u16` in there.
668 #[stable(feature = "rust1", since = "1.0.0")]
671 #[doc(primitive = "u64")]
673 /// The 64-bit unsigned integer type.
675 /// *[See also the `std::u64` module](u64/index.html).*
677 /// However, please note that examples are shared between primitive integer
678 /// types. So it's normal if you see usage of types like `u8` in there.
680 #[stable(feature = "rust1", since = "1.0.0")]
683 #[doc(primitive = "u128")]
685 /// The 128-bit unsigned integer type.
687 /// *[See also the `std::u128` module](u128/index.html).*
689 /// However, please note that examples are shared between primitive integer
690 /// types. So it's normal if you see usage of types like `u8` in there.
692 #[unstable(feature = "i128", issue="35118")]
695 #[doc(primitive = "isize")]
697 /// The pointer-sized signed integer type.
699 /// *[See also the `std::isize` module](isize/index.html).*
701 /// However, please note that examples are shared between primitive integer
702 /// types. So it's normal if you see usage of types like `usize` in there.
704 #[stable(feature = "rust1", since = "1.0.0")]
707 #[doc(primitive = "usize")]
709 /// The pointer-sized unsigned integer type.
711 /// *[See also the `std::usize` module](usize/index.html).*
713 /// However, please note that examples are shared between primitive integer
714 /// types. So it's normal if you see usage of types like `isize` in there.
716 #[stable(feature = "rust1", since = "1.0.0")]