]> git.proxmox.com Git - rustc.git/blob - src/libstd/primitive_docs.rs
Imported Upstream version 1.9.0+dfsg1
[rustc.git] / 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.
4 //
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.
10
11 #[doc(primitive = "bool")]
12 //
13 /// The boolean type.
14 ///
15 /// The `bool` represents a value, which could only be either `true` or `false`.
16 ///
17 /// # Basic usage
18 ///
19 /// `bool` implements various traits, such as [`BitAnd`], [`BitOr`], [`Not`], etc.,
20 /// which allow us to perform boolean operations using `&`, `|` and `!`.
21 ///
22 /// [`if`] always demands a `bool` value. [`assert!`], being an important macro in testing,
23 /// checks whether an expression returns `true`.
24 ///
25 /// ```
26 /// let bool_val = true & false | false;
27 /// assert!(!bool_val);
28 /// ```
29 ///
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
35 ///
36 /// # Examples
37 ///
38 /// A trivial example of the usage of `bool`,
39 ///
40 /// ```
41 /// let praise_the_borrow_checker = true;
42 ///
43 /// // using the `if` conditional
44 /// if praise_the_borrow_checker {
45 /// println!("oh, yeah!");
46 /// } else {
47 /// println!("what?!!");
48 /// }
49 ///
50 /// // ... or, a match pattern
51 /// match praise_the_borrow_checker {
52 /// true => println!("keep praising!"),
53 /// false => println!("you should praise!"),
54 /// }
55 /// ```
56 ///
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).
59 mod prim_bool { }
60
61 #[doc(primitive = "char")]
62 //
63 /// A character type.
64 ///
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
68 /// point]'.
69 ///
70 /// [Unicode scalar value]: http://www.unicode.org/glossary/#unicode_scalar_value
71 /// [Unicode code point]: http://www.unicode.org/glossary/#code_point
72 ///
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.
76 ///
77 /// # Representation
78 ///
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:
81 ///
82 /// ```
83 /// let v = vec!['h', 'e', 'l', 'l', 'o'];
84 ///
85 /// // five elements times four bytes for each element
86 /// assert_eq!(20, v.len() * std::mem::size_of::<char>());
87 ///
88 /// let s = String::from("hello");
89 ///
90 /// // five elements times one byte per element
91 /// assert_eq!(5, s.len() * std::mem::size_of::<u8>());
92 /// ```
93 ///
94 /// [`String`]: string/struct.String.html
95 ///
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:
99 ///
100 /// ```
101 /// let s = String::from("❤️");
102 ///
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());
108 /// ```
109 ///
110 /// This means it won't fit into a `char`. Trying to create a literal with
111 /// `let heart = '❤️';` gives an error:
112 ///
113 /// ```text
114 /// error: character literal may only contain one codepoint: '❤
115 /// let heart = '❤️';
116 /// ^~
117 /// ```
118 ///
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:
121 ///
122 /// ```
123 /// let s = String::from("love: ❤️");
124 /// let v: Vec<char> = s.chars().collect();
125 ///
126 /// assert_eq!(12, s.len() * std::mem::size_of::<u8>());
127 /// assert_eq!(32, v.len() * std::mem::size_of::<char>());
128 /// ```
129 mod prim_char { }
130
131 #[doc(primitive = "unit")]
132 //
133 /// The `()` type, sometimes called "unit" or "nil".
134 ///
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:
139 ///
140 /// ```rust
141 /// fn long() -> () {}
142 ///
143 /// fn short() {}
144 /// ```
145 ///
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,
149 ///
150 /// ```rust
151 /// fn returns_i64() -> i64 {
152 /// 1i64
153 /// }
154 /// fn returns_unit() {
155 /// 1i64;
156 /// }
157 ///
158 /// let is_i64 = {
159 /// returns_i64()
160 /// };
161 /// let is_unit = {
162 /// returns_i64();
163 /// };
164 /// ```
165 ///
166 mod prim_unit { }
167
168 #[doc(primitive = "pointer")]
169 //
170 /// Raw, unsafe pointers, `*const T`, and `*mut T`.
171 ///
172 /// Working with raw pointers in Rust is uncommon,
173 /// typically limited to a few patterns.
174 ///
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.
178 ///
179 /// # Common ways to create raw pointers
180 ///
181 /// ## 1. Coerce a reference (`&T`) or mutable reference (`&mut T`).
182 ///
183 /// ```
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;
188 /// ```
189 ///
190 /// To get a pointer to a boxed value, dereference the box:
191 ///
192 /// ```
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;
197 /// ```
198 ///
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.
202 ///
203 /// ## 2. Consume a box (`Box<T>`).
204 ///
205 /// The `into_raw` function consumes a box and returns
206 /// the raw pointer. It doesn't destroy `T` or deallocate any memory.
207 ///
208 /// ```
209 /// let my_speed: Box<i32> = Box::new(88);
210 /// let my_speed: *mut i32 = Box::into_raw(my_speed);
211 ///
212 /// // By taking ownership of the original `Box<T>` though
213 /// // we are obligated to put it together later to be destroyed.
214 /// unsafe {
215 /// drop(Box::from_raw(my_speed));
216 /// }
217 /// ```
218 ///
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.
221 ///
222 /// ## 3. Get it from C.
223 ///
224 /// ```
225 /// # #![feature(libc)]
226 /// extern crate libc;
227 ///
228 /// use std::mem;
229 ///
230 /// fn main() {
231 /// unsafe {
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");
235 /// }
236 /// libc::free(my_num as *mut libc::c_void);
237 /// }
238 /// }
239 /// ```
240 ///
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.
244 ///
245 /// *[See also the `std::ptr` module](ptr/index.html).*
246 ///
247 mod prim_pointer { }
248
249 #[doc(primitive = "array")]
250 //
251 /// A fixed-size array, denoted `[T; N]`, for the element type, `T`, and the
252 /// non-negative compile time constant size, `N`.
253 ///
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`.
257 ///
258 /// The type `[T; N]` is `Copy` if `T: Copy`.
259 ///
260 /// Arrays of sizes from 0 to 32 (inclusive) implement the following traits if
261 /// the element type allows it:
262 ///
263 /// - `Clone` (only if `T: Copy`)
264 /// - `Debug`
265 /// - `IntoIterator` (implemented for `&[T; N]` and `&mut [T; N]`)
266 /// - `PartialEq`, `PartialOrd`, `Ord`, `Eq`
267 /// - `Hash`
268 /// - `AsRef`, `AsMut`
269 /// - `Borrow`, `BorrowMut`
270 /// - `Default`
271 ///
272 /// Arrays coerce to [slices (`[T]`)][slice], so their methods can be called on
273 /// arrays.
274 ///
275 /// [slice]: primitive.slice.html
276 ///
277 /// Rust does not currently support generics over the size of an array type.
278 ///
279 /// # Examples
280 ///
281 /// ```
282 /// let mut array: [i32; 3] = [0; 3];
283 ///
284 /// array[1] = 1;
285 /// array[2] = 2;
286 ///
287 /// assert_eq!([1, 2], &array[1..]);
288 ///
289 /// // This loop prints: 0 1 2
290 /// for x in &array {
291 /// print!("{} ", x);
292 /// }
293 ///
294 /// ```
295 ///
296 mod prim_array { }
297
298 #[doc(primitive = "slice")]
299 //
300 /// A dynamically-sized view into a contiguous sequence, `[T]`.
301 ///
302 /// Slices are a view into a block of memory represented as a pointer and a
303 /// length.
304 ///
305 /// ```
306 /// // slicing a Vec
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"];
311 /// ```
312 ///
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
316 /// points to:
317 ///
318 /// ```
319 /// let x = &mut [1, 2, 3];
320 /// x[1] = 7;
321 /// assert_eq!(x, &[1, 7, 3]);
322 /// ```
323 ///
324 /// *[See also the `std::slice` module](slice/index.html).*
325 ///
326 mod prim_slice { }
327
328 #[doc(primitive = "str")]
329 //
330 /// String slices.
331 ///
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`.
335 ///
336 /// Strings slices are always valid UTF-8.
337 ///
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.
341 ///
342 /// # Examples
343 ///
344 /// String literals are string slices:
345 ///
346 /// ```
347 /// let hello = "Hello, world!";
348 ///
349 /// // with an explicit type annotation
350 /// let hello: &'static str = "Hello, world!";
351 /// ```
352 ///
353 /// They are `'static` because they're stored directly in the final binary, and
354 /// so will be valid for the `'static` duration.
355 ///
356 /// # Representation
357 ///
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:
360 ///
361 /// ```
362 /// use std::slice;
363 /// use std::str;
364 ///
365 /// let story = "Once upon a time...";
366 ///
367 /// let ptr = story.as_ptr();
368 /// let len = story.len();
369 ///
370 /// // story has nineteen bytes
371 /// assert_eq!(19, len);
372 ///
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:
375 /// let s = unsafe {
376 /// // First, we build a &[u8]...
377 /// let slice = slice::from_raw_parts(ptr, len);
378 ///
379 /// // ... and then convert that slice into a string slice
380 /// str::from_utf8(slice)
381 /// };
382 ///
383 /// assert_eq!(s, Ok(story));
384 /// ```
385 ///
386 /// [`.as_ptr()`]: #method.as_ptr
387 /// [`len()`]: #method.len
388 mod prim_str { }
389
390 #[doc(primitive = "tuple")]
391 //
392 /// A finite heterogeneous sequence, `(T, U, ..)`.
393 ///
394 /// Let's cover each of those in turn:
395 ///
396 /// Tuples are *finite*. In other words, a tuple has a length. Here's a tuple
397 /// of length `3`:
398 ///
399 /// ```
400 /// ("hello", 5, 'c');
401 /// ```
402 ///
403 /// 'Length' is also sometimes called 'arity' here; each tuple of a different
404 /// length is a different, distinct type.
405 ///
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:
408 ///
409 /// ```rust,ignore
410 /// (&'static str, i32, char)
411 /// ```
412 ///
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:
415 ///
416 /// ```rust
417 /// let tuple = ("hello", 5, 'c');
418 ///
419 /// assert_eq!(tuple.0, "hello");
420 /// assert_eq!(tuple.1, 5);
421 /// assert_eq!(tuple.2, 'c');
422 /// ```
423 ///
424 /// For more about tuples, see [the book](../book/primitive-types.html#tuples).
425 ///
426 /// # Trait implementations
427 ///
428 /// If every type inside a tuple implements one of the following traits, then a
429 /// tuple itself also implements it.
430 ///
431 /// * [`Clone`]
432 /// * [`Copy`]
433 /// * [`PartialEq`]
434 /// * [`Eq`]
435 /// * [`PartialOrd`]
436 /// * [`Ord`]
437 /// * [`Debug`]
438 /// * [`Default`]
439 /// * [`Hash`]
440 ///
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
450 ///
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.
453 ///
454 /// # Examples
455 ///
456 /// Basic usage:
457 ///
458 /// ```
459 /// let tuple = ("hello", 5, 'c');
460 ///
461 /// assert_eq!(tuple.0, "hello");
462 /// ```
463 ///
464 /// Tuples are often used as a return type when you want to return more than
465 /// one value:
466 ///
467 /// ```
468 /// fn calculate_point() -> (i32, i32) {
469 /// // Don't do a calculation, that's not the point of the example
470 /// (4, 5)
471 /// }
472 ///
473 /// let point = calculate_point();
474 ///
475 /// assert_eq!(point.0, 4);
476 /// assert_eq!(point.1, 5);
477 ///
478 /// // Combining this with patterns can be nicer.
479 ///
480 /// let (x, y) = calculate_point();
481 ///
482 /// assert_eq!(x, 4);
483 /// assert_eq!(y, 5);
484 /// ```
485 ///
486 mod prim_tuple { }
487
488 #[doc(primitive = "f32")]
489 /// The 32-bit floating point type.
490 ///
491 /// *[See also the `std::f32` module](f32/index.html).*
492 ///
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.
495 ///
496 mod prim_f32 { }
497
498 #[doc(primitive = "f64")]
499 //
500 /// The 64-bit floating point type.
501 ///
502 /// *[See also the `std::f64` module](f64/index.html).*
503 ///
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.
506 ///
507 mod prim_f64 { }
508
509 #[doc(primitive = "i8")]
510 //
511 /// The 8-bit signed integer type.
512 ///
513 /// *[See also the `std::i8` module](i8/index.html).*
514 ///
515 mod prim_i8 { }
516
517 #[doc(primitive = "i16")]
518 //
519 /// The 16-bit signed integer type.
520 ///
521 /// *[See also the `std::i16` module](i16/index.html).*
522 ///
523 mod prim_i16 { }
524
525 #[doc(primitive = "i32")]
526 //
527 /// The 32-bit signed integer type.
528 ///
529 /// *[See also the `std::i32` module](i32/index.html).*
530 ///
531 mod prim_i32 { }
532
533 #[doc(primitive = "i64")]
534 //
535 /// The 64-bit signed integer type.
536 ///
537 /// *[See also the `std::i64` module](i64/index.html).*
538 ///
539 mod prim_i64 { }
540
541 #[doc(primitive = "u8")]
542 //
543 /// The 8-bit unsigned integer type.
544 ///
545 /// *[See also the `std::u8` module](u8/index.html).*
546 ///
547 mod prim_u8 { }
548
549 #[doc(primitive = "u16")]
550 //
551 /// The 16-bit unsigned integer type.
552 ///
553 /// *[See also the `std::u16` module](u16/index.html).*
554 ///
555 mod prim_u16 { }
556
557 #[doc(primitive = "u32")]
558 //
559 /// The 32-bit unsigned integer type.
560 ///
561 /// *[See also the `std::u32` module](u32/index.html).*
562 ///
563 mod prim_u32 { }
564
565 #[doc(primitive = "u64")]
566 //
567 /// The 64-bit unsigned integer type.
568 ///
569 /// *[See also the `std::u64` module](u64/index.html).*
570 ///
571 mod prim_u64 { }
572
573 #[doc(primitive = "isize")]
574 //
575 /// The pointer-sized signed integer type.
576 ///
577 /// *[See also the `std::isize` module](isize/index.html).*
578 ///
579 mod prim_isize { }
580
581 #[doc(primitive = "usize")]
582 //
583 /// The pointer-sized unsigned integer type.
584 ///
585 /// *[See also the `std::usize` module](usize/index.html).*
586 ///
587 mod prim_usize { }