]>
git.proxmox.com Git - rustc.git/blob - src/libstd/primitive_docs.rs
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`.
19 /// `bool` implements various traits, such as [`BitAnd`], [`BitOr`], [`Not`], etc.,
20 /// which allow us to perform boolean operations using `&`, `|` and `!`.
22 /// [`if`] always demands a `bool` value. [`assert!`], being an important macro in testing,
23 /// checks whether an expression returns `true`.
26 /// let bool_val = true & false | false;
27 /// assert!(!bool_val);
30 /// [`assert!`]: macro.assert!.html
31 /// [`if` conditionals]: ../book/if.html
32 /// [`BitAnd`]: ops/trait.BitAnd.html
33 /// [`BitOr`]: ops/trait.BitOr.html
34 /// [`Not`]: ops/trait.Not.html
38 /// A trivial example of the usage of `bool`,
41 /// let praise_the_borrow_checker = true;
43 /// // using the `if` conditional
44 /// if praise_the_borrow_checker {
45 /// println!("oh, yeah!");
47 /// println!("what?!!");
50 /// // ... or, a match pattern
51 /// match praise_the_borrow_checker {
52 /// true => println!("keep praising!"),
53 /// false => println!("you should praise!"),
57 /// Also, since `bool` implements the [`Copy`](marker/trait.Copy.html) trait, we don't
58 /// have to worry about the move semantics (just like the integer and float primitives).
61 #[doc(primitive = "char")]
65 /// The `char` type represents a single character. More specifically, since
66 /// 'character' isn't a well-defined concept in Unicode, `char` is a '[Unicode
67 /// scalar value]', which is similar to, but not the same as, a '[Unicode code
70 /// [Unicode scalar value]: http://www.unicode.org/glossary/#unicode_scalar_value
71 /// [Unicode code point]: http://www.unicode.org/glossary/#code_point
73 /// This documentation describes a number of methods and trait implementations on the
74 /// `char` type. For technical reasons, there is additional, separate
75 /// documentation in [the `std::char` module](char/index.html) as well.
79 /// `char` is always four bytes in size. This is a different representation than
80 /// a given character would have as part of a [`String`]. For example:
83 /// let v = vec!['h', 'e', 'l', 'l', 'o'];
85 /// // five elements times four bytes for each element
86 /// assert_eq!(20, v.len() * std::mem::size_of::<char>());
88 /// let s = String::from("hello");
90 /// // five elements times one byte per element
91 /// assert_eq!(5, s.len() * std::mem::size_of::<u8>());
94 /// [`String`]: string/struct.String.html
96 /// As always, remember that a human intuition for 'character' may not map to
97 /// Unicode's definitions. For example, emoji symbols such as '❤️' can be more
98 /// than one Unicode code point; this ❤️ in particular is two:
101 /// let s = String::from("❤️");
103 /// // we get two chars out of a single ❤️
104 /// let mut iter = s.chars();
105 /// assert_eq!(Some('\u{2764}'), iter.next());
106 /// assert_eq!(Some('\u{fe0f}'), iter.next());
107 /// assert_eq!(None, iter.next());
110 /// This means it won't fit into a `char`. Trying to create a literal with
111 /// `let heart = '❤️';` gives an error:
114 /// error: character literal may only contain one codepoint: '❤
115 /// let heart = '❤️';
119 /// Another implication of the 4-byte fixed size of a `char` is that
120 /// per-`char` processing can end up using a lot more memory:
123 /// let s = String::from("love: ❤️");
124 /// let v: Vec<char> = s.chars().collect();
126 /// assert_eq!(12, s.len() * std::mem::size_of::<u8>());
127 /// assert_eq!(32, v.len() * std::mem::size_of::<char>());
131 #[doc(primitive = "unit")]
133 /// The `()` type, sometimes called "unit" or "nil".
135 /// The `()` type has exactly one value `()`, and is used when there
136 /// is no other meaningful value that could be returned. `()` is most
137 /// commonly seen implicitly: functions without a `-> ...` implicitly
138 /// have return type `()`, that is, these are equivalent:
141 /// fn long() -> () {}
146 /// The semicolon `;` can be used to discard the result of an
147 /// expression at the end of a block, making the expression (and thus
148 /// the block) evaluate to `()`. For example,
151 /// fn returns_i64() -> i64 {
154 /// fn returns_unit() {
168 #[doc(primitive = "pointer")]
170 /// Raw, unsafe pointers, `*const T`, and `*mut T`.
172 /// Working with raw pointers in Rust is uncommon,
173 /// typically limited to a few patterns.
175 /// Use the `null` function to create null pointers, and the `is_null` method
176 /// of the `*const T` type to check for null. The `*const T` type also defines
177 /// the `offset` method, for pointer math.
179 /// # Common ways to create raw pointers
181 /// ## 1. Coerce a reference (`&T`) or mutable reference (`&mut T`).
184 /// let my_num: i32 = 10;
185 /// let my_num_ptr: *const i32 = &my_num;
186 /// let mut my_speed: i32 = 88;
187 /// let my_speed_ptr: *mut i32 = &mut my_speed;
190 /// To get a pointer to a boxed value, dereference the box:
193 /// let my_num: Box<i32> = Box::new(10);
194 /// let my_num_ptr: *const i32 = &*my_num;
195 /// let mut my_speed: Box<i32> = Box::new(88);
196 /// let my_speed_ptr: *mut i32 = &mut *my_speed;
199 /// This does not take ownership of the original allocation
200 /// and requires no resource management later,
201 /// but you must not use the pointer after its lifetime.
203 /// ## 2. Consume a box (`Box<T>`).
205 /// The `into_raw` function consumes a box and returns
206 /// the raw pointer. It doesn't destroy `T` or deallocate any memory.
209 /// let my_speed: Box<i32> = Box::new(88);
210 /// let my_speed: *mut i32 = Box::into_raw(my_speed);
212 /// // By taking ownership of the original `Box<T>` though
213 /// // we are obligated to put it together later to be destroyed.
215 /// drop(Box::from_raw(my_speed));
219 /// Note that here the call to `drop` is for clarity - it indicates
220 /// that we are done with the given value and it should be destroyed.
222 /// ## 3. Get it from C.
225 /// # #![feature(libc)]
226 /// extern crate libc;
232 /// let my_num: *mut i32 = libc::malloc(mem::size_of::<i32>() as libc::size_t) as *mut i32;
233 /// if my_num.is_null() {
234 /// panic!("failed to allocate memory");
236 /// libc::free(my_num as *mut libc::c_void);
241 /// Usually you wouldn't literally use `malloc` and `free` from Rust,
242 /// but C APIs hand out a lot of pointers generally, so are a common source
243 /// of raw pointers in Rust.
245 /// *[See also the `std::ptr` module](ptr/index.html).*
249 #[doc(primitive = "array")]
251 /// A fixed-size array, denoted `[T; N]`, for the element type, `T`, and the
252 /// non-negative compile time constant size, `N`.
254 /// Arrays values are created either with an explicit expression that lists
255 /// each element: `[x, y, z]` or a repeat expression: `[x; N]`. The repeat
256 /// expression requires that the element type is `Copy`.
258 /// The type `[T; N]` is `Copy` if `T: Copy`.
260 /// Arrays of sizes from 0 to 32 (inclusive) implement the following traits if
261 /// the element type allows it:
263 /// - `Clone` (only if `T: Copy`)
265 /// - `IntoIterator` (implemented for `&[T; N]` and `&mut [T; N]`)
266 /// - `PartialEq`, `PartialOrd`, `Ord`, `Eq`
268 /// - `AsRef`, `AsMut`
269 /// - `Borrow`, `BorrowMut`
272 /// Arrays coerce to [slices (`[T]`)][slice], so their methods can be called on
275 /// [slice]: primitive.slice.html
277 /// Rust does not currently support generics over the size of an array type.
282 /// let mut array: [i32; 3] = [0; 3];
287 /// assert_eq!([1, 2], &array[1..]);
289 /// // This loop prints: 0 1 2
290 /// for x in &array {
291 /// print!("{} ", x);
298 #[doc(primitive = "slice")]
300 /// A dynamically-sized view into a contiguous sequence, `[T]`.
302 /// Slices are a view into a block of memory represented as a pointer and a
307 /// let vec = vec![1, 2, 3];
308 /// let int_slice = &vec[..];
309 /// // coercing an array to a slice
310 /// let str_slice: &[&str] = &["one", "two", "three"];
313 /// Slices are either mutable or shared. The shared slice type is `&[T]`,
314 /// while the mutable slice type is `&mut [T]`, where `T` represents the element
315 /// type. For example, you can mutate the block of memory that a mutable slice
319 /// let x = &mut [1, 2, 3];
321 /// assert_eq!(x, &[1, 7, 3]);
324 /// *[See also the `std::slice` module](slice/index.html).*
328 #[doc(primitive = "str")]
332 /// The `str` type, also called a 'string slice', is the most primitive string
333 /// type. It is usually seen in its borrowed form, `&str`. It is also the type
334 /// of string literals, `&'static str`.
336 /// Strings slices are always valid UTF-8.
338 /// This documentation describes a number of methods and trait implementations
339 /// on the `str` type. For technical reasons, there is additional, separate
340 /// documentation in [the `std::str` module](str/index.html) as well.
344 /// String literals are string slices:
347 /// let hello = "Hello, world!";
349 /// // with an explicit type annotation
350 /// let hello: &'static str = "Hello, world!";
353 /// They are `'static` because they're stored directly in the final binary, and
354 /// so will be valid for the `'static` duration.
358 /// A `&str` is made up of two components: a pointer to some bytes, and a
359 /// length. You can look at these with the [`.as_ptr()`] and [`len()`] methods:
365 /// let story = "Once upon a time...";
367 /// let ptr = story.as_ptr();
368 /// let len = story.len();
370 /// // story has nineteen bytes
371 /// assert_eq!(19, len);
373 /// // We can re-build a str out of ptr and len. This is all unsafe because
374 /// // we are responsible for making sure the two components are valid:
376 /// // First, we build a &[u8]...
377 /// let slice = slice::from_raw_parts(ptr, len);
379 /// // ... and then convert that slice into a string slice
380 /// str::from_utf8(slice)
383 /// assert_eq!(s, Ok(story));
386 /// [`.as_ptr()`]: #method.as_ptr
387 /// [`len()`]: #method.len
390 #[doc(primitive = "tuple")]
392 /// A finite heterogeneous sequence, `(T, U, ..)`.
394 /// Let's cover each of those in turn:
396 /// Tuples are *finite*. In other words, a tuple has a length. Here's a tuple
400 /// ("hello", 5, 'c');
403 /// 'Length' is also sometimes called 'arity' here; each tuple of a different
404 /// length is a different, distinct type.
406 /// Tuples are *heterogeneous*. This means that each element of the tuple can
407 /// have a different type. In that tuple above, it has the type:
410 /// (&'static str, i32, char)
413 /// Tuples are a *sequence*. This means that they can be accessed by position;
414 /// this is called 'tuple indexing', and it looks like this:
417 /// let tuple = ("hello", 5, 'c');
419 /// assert_eq!(tuple.0, "hello");
420 /// assert_eq!(tuple.1, 5);
421 /// assert_eq!(tuple.2, 'c');
424 /// For more about tuples, see [the book](../book/primitive-types.html#tuples).
426 /// # Trait implementations
428 /// If every type inside a tuple implements one of the following traits, then a
429 /// tuple itself also implements it.
441 /// [`Clone`]: clone/trait.Clone.html
442 /// [`Copy`]: marker/trait.Copy.html
443 /// [`PartialEq`]: cmp/trait.PartialEq.html
444 /// [`Eq`]: cmp/trait.Eq.html
445 /// [`PartialOrd`]: cmp/trait.PartialOrd.html
446 /// [`Ord`]: cmp/trait.Ord.html
447 /// [`Debug`]: fmt/trait.Debug.html
448 /// [`Default`]: default/trait.Default.html
449 /// [`Hash`]: hash/trait.Hash.html
451 /// Due to a temporary restriction in Rust's type system, these traits are only
452 /// implemented on tuples of arity 32 or less. In the future, this may change.
459 /// let tuple = ("hello", 5, 'c');
461 /// assert_eq!(tuple.0, "hello");
464 /// Tuples are often used as a return type when you want to return more than
468 /// fn calculate_point() -> (i32, i32) {
469 /// // Don't do a calculation, that's not the point of the example
473 /// let point = calculate_point();
475 /// assert_eq!(point.0, 4);
476 /// assert_eq!(point.1, 5);
478 /// // Combining this with patterns can be nicer.
480 /// let (x, y) = calculate_point();
482 /// assert_eq!(x, 4);
483 /// assert_eq!(y, 5);
488 #[doc(primitive = "f32")]
489 /// The 32-bit floating point type.
491 /// *[See also the `std::f32` module](f32/index.html).*
493 /// However, please note that examples are shared between the `f64` and `f32`
494 /// primitive types. So it's normal if you see usage of `f64` in there.
498 #[doc(primitive = "f64")]
500 /// The 64-bit floating point type.
502 /// *[See also the `std::f64` module](f64/index.html).*
504 /// However, please note that examples are shared between the `f64` and `f32`
505 /// primitive types. So it's normal if you see usage of `f32` in there.
509 #[doc(primitive = "i8")]
511 /// The 8-bit signed integer type.
513 /// *[See also the `std::i8` module](i8/index.html).*
517 #[doc(primitive = "i16")]
519 /// The 16-bit signed integer type.
521 /// *[See also the `std::i16` module](i16/index.html).*
525 #[doc(primitive = "i32")]
527 /// The 32-bit signed integer type.
529 /// *[See also the `std::i32` module](i32/index.html).*
533 #[doc(primitive = "i64")]
535 /// The 64-bit signed integer type.
537 /// *[See also the `std::i64` module](i64/index.html).*
541 #[doc(primitive = "u8")]
543 /// The 8-bit unsigned integer type.
545 /// *[See also the `std::u8` module](u8/index.html).*
549 #[doc(primitive = "u16")]
551 /// The 16-bit unsigned integer type.
553 /// *[See also the `std::u16` module](u16/index.html).*
557 #[doc(primitive = "u32")]
559 /// The 32-bit unsigned integer type.
561 /// *[See also the `std::u32` module](u32/index.html).*
565 #[doc(primitive = "u64")]
567 /// The 64-bit unsigned integer type.
569 /// *[See also the `std::u64` module](u64/index.html).*
573 #[doc(primitive = "isize")]
575 /// The pointer-sized signed integer type.
577 /// *[See also the `std::isize` module](isize/index.html).*
581 #[doc(primitive = "usize")]
583 /// The pointer-sized unsigned integer type.
585 /// *[See also the `std::usize` module](usize/index.html).*