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")]
17 #[doc(primitive = "char")]
21 /// The `char` type represents a single character. More specifically, since
22 /// 'character' isn't a well-defined concept in Unicode, `char` is a '[Unicode
23 /// scalar value]', which is similar to, but not the same as, a '[Unicode code
26 /// [Unicode scalar value]: http://www.unicode.org/glossary/#unicode_scalar_value
27 /// [Unicode code point]: http://www.unicode.org/glossary/#code_point
29 /// This documentation describes a number of methods and trait implementations on the
30 /// `char` type. For technical reasons, there is additional, separate
31 /// documentation in [the `std::char` module](char/index.html) as well.
35 /// `char` is always four bytes in size. This is a different representation than
36 /// a given character would have as part of a [`String`], for example:
39 /// let v = vec!['h', 'e', 'l', 'l', 'o'];
41 /// // five elements times four bytes for each element
42 /// assert_eq!(20, v.len() * std::mem::size_of::<char>());
44 /// let s = String::from("hello");
46 /// // five elements times one byte per element
47 /// assert_eq!(5, s.len() * std::mem::size_of::<u8>());
50 /// [`String`]: string/struct.String.html
52 /// As always, remember that a human intuition for 'character' may not map to
53 /// Unicode's definitions. For example, emoji symbols such as '❤️' are more than
54 /// one byte; ❤️ in particular is six:
57 /// let s = String::from("❤️");
59 /// // six bytes times one byte for each element
60 /// assert_eq!(6, s.len() * std::mem::size_of::<u8>());
63 /// This also means it won't fit into a `char`, and so trying to create a
64 /// literal with `let heart = '❤️';` gives an error:
67 /// error: character literal may only contain one codepoint: '❤
72 /// Another implication of this is that if you want to do per-`char`acter
73 /// processing, it can end up using a lot more memory:
76 /// let s = String::from("love: ❤️");
77 /// let v: Vec<char> = s.chars().collect();
79 /// assert_eq!(12, s.len() * std::mem::size_of::<u8>());
80 /// assert_eq!(32, v.len() * std::mem::size_of::<char>());
83 /// Or may give you results you may not expect:
86 /// let s = String::from("❤️");
88 /// let mut iter = s.chars();
90 /// // we get two chars out of a single ❤️
91 /// assert_eq!(Some('\u{2764}'), iter.next());
92 /// assert_eq!(Some('\u{fe0f}'), iter.next());
93 /// assert_eq!(None, iter.next());
97 #[doc(primitive = "unit")]
99 /// The `()` type, sometimes called "unit" or "nil".
101 /// The `()` type has exactly one value `()`, and is used when there
102 /// is no other meaningful value that could be returned. `()` is most
103 /// commonly seen implicitly: functions without a `-> ...` implicitly
104 /// have return type `()`, that is, these are equivalent:
107 /// fn long() -> () {}
112 /// The semicolon `;` can be used to discard the result of an
113 /// expression at the end of a block, making the expression (and thus
114 /// the block) evaluate to `()`. For example,
117 /// fn returns_i64() -> i64 {
120 /// fn returns_unit() {
134 #[doc(primitive = "pointer")]
136 /// Raw, unsafe pointers, `*const T`, and `*mut T`.
138 /// Working with raw pointers in Rust is uncommon,
139 /// typically limited to a few patterns.
141 /// Use the `null` function to create null pointers, and the `is_null` method
142 /// of the `*const T` type to check for null. The `*const T` type also defines
143 /// the `offset` method, for pointer math.
145 /// # Common ways to create raw pointers
147 /// ## 1. Coerce a reference (`&T`) or mutable reference (`&mut T`).
150 /// let my_num: i32 = 10;
151 /// let my_num_ptr: *const i32 = &my_num;
152 /// let mut my_speed: i32 = 88;
153 /// let my_speed_ptr: *mut i32 = &mut my_speed;
156 /// To get a pointer to a boxed value, dereference the box:
159 /// let my_num: Box<i32> = Box::new(10);
160 /// let my_num_ptr: *const i32 = &*my_num;
161 /// let mut my_speed: Box<i32> = Box::new(88);
162 /// let my_speed_ptr: *mut i32 = &mut *my_speed;
165 /// This does not take ownership of the original allocation
166 /// and requires no resource management later,
167 /// but you must not use the pointer after its lifetime.
169 /// ## 2. Consume a box (`Box<T>`).
171 /// The `into_raw` function consumes a box and returns
172 /// the raw pointer. It doesn't destroy `T` or deallocate any memory.
175 /// let my_speed: Box<i32> = Box::new(88);
176 /// let my_speed: *mut i32 = Box::into_raw(my_speed);
178 /// // By taking ownership of the original `Box<T>` though
179 /// // we are obligated to put it together later to be destroyed.
181 /// drop(Box::from_raw(my_speed));
185 /// Note that here the call to `drop` is for clarity - it indicates
186 /// that we are done with the given value and it should be destroyed.
188 /// ## 3. Get it from C.
191 /// # #![feature(libc)]
192 /// extern crate libc;
198 /// let my_num: *mut i32 = libc::malloc(mem::size_of::<i32>() as libc::size_t) as *mut i32;
199 /// if my_num.is_null() {
200 /// panic!("failed to allocate memory");
202 /// libc::free(my_num as *mut libc::c_void);
207 /// Usually you wouldn't literally use `malloc` and `free` from Rust,
208 /// but C APIs hand out a lot of pointers generally, so are a common source
209 /// of raw pointers in Rust.
211 /// *[See also the `std::ptr` module](ptr/index.html).*
215 #[doc(primitive = "array")]
217 /// A fixed-size array, denoted `[T; N]`, for the element type, `T`, and the
218 /// non-negative compile time constant size, `N`.
220 /// Arrays values are created either with an explicit expression that lists
221 /// each element: `[x, y, z]` or a repeat expression: `[x; N]`. The repeat
222 /// expression requires that the element type is `Copy`.
224 /// The type `[T; N]` is `Copy` if `T: Copy`.
226 /// Arrays of sizes from 0 to 32 (inclusive) implement the following traits if
227 /// the element type allows it:
229 /// - `Clone` (only if `T: Copy`)
231 /// - `IntoIterator` (implemented for `&[T; N]` and `&mut [T; N]`)
232 /// - `PartialEq`, `PartialOrd`, `Ord`, `Eq`
234 /// - `AsRef`, `AsMut`
235 /// - `Borrow`, `BorrowMut`
238 /// Arrays coerce to [slices (`[T]`)][slice], so their methods can be called on
241 /// [slice]: primitive.slice.html
243 /// Rust does not currently support generics over the size of an array type.
248 /// let mut array: [i32; 3] = [0; 3];
253 /// assert_eq!([1, 2], &array[1..]);
255 /// // This loop prints: 0 1 2
256 /// for x in &array {
257 /// print!("{} ", x);
264 #[doc(primitive = "slice")]
266 /// A dynamically-sized view into a contiguous sequence, `[T]`.
268 /// Slices are a view into a block of memory represented as a pointer and a
273 /// let vec = vec![1, 2, 3];
274 /// let int_slice = &vec[..];
275 /// // coercing an array to a slice
276 /// let str_slice: &[&str] = &["one", "two", "three"];
279 /// Slices are either mutable or shared. The shared slice type is `&[T]`,
280 /// while the mutable slice type is `&mut [T]`, where `T` represents the element
281 /// type. For example, you can mutate the block of memory that a mutable slice
285 /// let x = &mut [1, 2, 3];
287 /// assert_eq!(x, &[1, 7, 3]);
290 /// *[See also the `std::slice` module](slice/index.html).*
294 #[doc(primitive = "str")]
298 /// The `str` type, also called a 'string slice', is the most primitive string
299 /// type. It is usually seen in its borrowed form, `&str`. It is also the type
300 /// of string literals, `&'static str`.
302 /// Strings slices are always valid UTF-8.
304 /// This documentation describes a number of methods and trait implementations
305 /// on the `str` type. For technical reasons, there is additional, separate
306 /// documentation in [the `std::str` module](str/index.html) as well.
310 /// String literals are string slices:
313 /// let hello = "Hello, world!";
315 /// // with an explicit type annotation
316 /// let hello: &'static str = "Hello, world!";
319 /// They are `'static` because they're stored directly in the final binary, and
320 /// so will be valid for the `'static` duration.
324 /// A `&str` is made up of two components: a pointer to some bytes, and a
325 /// length. You can look at these with the [`.as_ptr()`] and [`len()`] methods:
331 /// let story = "Once upon a time...";
333 /// let ptr = story.as_ptr();
334 /// let len = story.len();
336 /// // story has nineteen bytes
337 /// assert_eq!(19, len);
339 /// // We can re-build a str out of ptr and len. This is all unsafe becuase
340 /// // we are responsible for making sure the two components are valid:
342 /// // First, we build a &[u8]...
343 /// let slice = slice::from_raw_parts(ptr, len);
345 /// // ... and then convert that slice into a string slice
346 /// str::from_utf8(slice)
349 /// assert_eq!(s, Ok(story));
352 /// [`.as_ptr()`]: #method.as_ptr
353 /// [`len()`]: #method.len
356 #[doc(primitive = "tuple")]
358 /// A finite heterogeneous sequence, `(T, U, ..)`.
360 /// To access the _N_-th element of a tuple one can use `N` itself
361 /// as a field of the tuple.
363 /// Indexing starts from zero, so `0` returns first value, `1`
364 /// returns second value, and so on. In general, a tuple with _S_
365 /// elements provides aforementioned fields from `0` to `S-1`.
367 /// If every type inside a tuple implements one of the following
368 /// traits, then a tuple itself also implements it.
381 /// Accessing elements of a tuple at specified indices:
384 /// let x = ("colorless", "green", "ideas", "sleep", "furiously");
385 /// assert_eq!(x.3, "sleep");
389 /// assert_eq!(v.0 * u.0 + v.1 * u.1, -12);
392 /// Using traits implemented for tuples:
399 /// let c = b.clone();
402 /// let d : (u32, f32) = Default::default();
403 /// assert_eq!(d, (0, 0.0f32));
408 #[doc(primitive = "f32")]
409 /// The 32-bit floating point type.
411 /// *[See also the `std::f32` module](f32/index.html).*
415 #[doc(primitive = "f64")]
417 /// The 64-bit floating point type.
419 /// *[See also the `std::f64` module](f64/index.html).*
423 #[doc(primitive = "i8")]
425 /// The 8-bit signed integer type.
427 /// *[See also the `std::i8` module](i8/index.html).*
431 #[doc(primitive = "i16")]
433 /// The 16-bit signed integer type.
435 /// *[See also the `std::i16` module](i16/index.html).*
439 #[doc(primitive = "i32")]
441 /// The 32-bit signed integer type.
443 /// *[See also the `std::i32` module](i32/index.html).*
447 #[doc(primitive = "i64")]
449 /// The 64-bit signed integer type.
451 /// *[See also the `std::i64` module](i64/index.html).*
455 #[doc(primitive = "u8")]
457 /// The 8-bit unsigned integer type.
459 /// *[See also the `std::u8` module](u8/index.html).*
463 #[doc(primitive = "u16")]
465 /// The 16-bit unsigned integer type.
467 /// *[See also the `std::u16` module](u16/index.html).*
471 #[doc(primitive = "u32")]
473 /// The 32-bit unsigned integer type.
475 /// *[See also the `std::u32` module](u32/index.html).*
479 #[doc(primitive = "u64")]
481 /// The 64-bit unsigned integer type.
483 /// *[See also the `std::u64` module](u64/index.html).*
487 #[doc(primitive = "isize")]
489 /// The pointer-sized signed integer type.
491 /// *[See also the `std::isize` module](isize/index.html).*
495 #[doc(primitive = "usize")]
497 /// The pointer-sized unsigned integer type.
499 /// *[See also the `std::usize` module](usize/index.html).*