]> git.lizzy.rs Git - rust.git/blob - src/libstd/primitive_docs.rs
Various minor/cosmetic improvements to code
[rust.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 #[doc(alias = "true")]
13 #[doc(alias = "false")]
14 //
15 /// The boolean type.
16 ///
17 /// The `bool` represents a value, which could only be either `true` or `false`. If you cast
18 /// a `bool` into an integer, `true` will be 1 and `false` will be 0.
19 ///
20 /// # Basic usage
21 ///
22 /// `bool` implements various traits, such as [`BitAnd`], [`BitOr`], [`Not`], etc.,
23 /// which allow us to perform boolean operations using `&`, `|` and `!`.
24 ///
25 /// `if` always demands a `bool` value. [`assert!`], being an important macro in testing,
26 /// checks whether an expression returns `true`.
27 ///
28 /// ```
29 /// let bool_val = true & false | false;
30 /// assert!(!bool_val);
31 /// ```
32 ///
33 /// [`assert!`]: macro.assert.html
34 /// [`BitAnd`]: ops/trait.BitAnd.html
35 /// [`BitOr`]: ops/trait.BitOr.html
36 /// [`Not`]: ops/trait.Not.html
37 ///
38 /// # Examples
39 ///
40 /// A trivial example of the usage of `bool`,
41 ///
42 /// ```
43 /// let praise_the_borrow_checker = true;
44 ///
45 /// // using the `if` conditional
46 /// if praise_the_borrow_checker {
47 ///     println!("oh, yeah!");
48 /// } else {
49 ///     println!("what?!!");
50 /// }
51 ///
52 /// // ... or, a match pattern
53 /// match praise_the_borrow_checker {
54 ///     true => println!("keep praising!"),
55 ///     false => println!("you should praise!"),
56 /// }
57 /// ```
58 ///
59 /// Also, since `bool` implements the [`Copy`](marker/trait.Copy.html) trait, we don't
60 /// have to worry about the move semantics (just like the integer and float primitives).
61 ///
62 /// Now an example of `bool` cast to integer type:
63 ///
64 /// ```
65 /// assert_eq!(true as i32, 1);
66 /// assert_eq!(false as i32, 0);
67 /// ```
68 #[stable(feature = "rust1", since = "1.0.0")]
69 mod prim_bool { }
70
71 #[doc(primitive = "never")]
72 #[doc(alias = "!")]
73 //
74 /// The `!` type, also called "never".
75 ///
76 /// `!` represents the type of computations which never resolve to any value at all. For example,
77 /// the [`exit`] function `fn exit(code: i32) -> !` exits the process without ever returning, and
78 /// so returns `!`.
79 ///
80 /// `break`, `continue` and `return` expressions also have type `!`. For example we are allowed to
81 /// write:
82 ///
83 /// ```
84 /// #![feature(never_type)]
85 /// # fn foo() -> u32 {
86 /// let x: ! = {
87 ///     return 123
88 /// };
89 /// # }
90 /// ```
91 ///
92 /// Although the `let` is pointless here, it illustrates the meaning of `!`. Since `x` is never
93 /// assigned a value (because `return` returns from the entire function), `x` can be given type
94 /// `!`. We could also replace `return 123` with a `panic!` or a never-ending `loop` and this code
95 /// would still be valid.
96 ///
97 /// A more realistic usage of `!` is in this code:
98 ///
99 /// ```
100 /// # fn get_a_number() -> Option<u32> { None }
101 /// # loop {
102 /// let num: u32 = match get_a_number() {
103 ///     Some(num) => num,
104 ///     None => break,
105 /// };
106 /// # }
107 /// ```
108 ///
109 /// Both match arms must produce values of type [`u32`], but since `break` never produces a value
110 /// at all we know it can never produce a value which isn't a [`u32`]. This illustrates another
111 /// behaviour of the `!` type - expressions with type `!` will coerce into any other type.
112 ///
113 /// [`u32`]: primitive.str.html
114 /// [`exit`]: process/fn.exit.html
115 ///
116 /// # `!` and generics
117 ///
118 /// ## Infallible errors
119 ///
120 /// The main place you'll see `!` used explicitly is in generic code. Consider the [`FromStr`]
121 /// trait:
122 ///
123 /// ```
124 /// trait FromStr: Sized {
125 ///     type Err;
126 ///     fn from_str(s: &str) -> Result<Self, Self::Err>;
127 /// }
128 /// ```
129 ///
130 /// When implementing this trait for [`String`] we need to pick a type for [`Err`]. And since
131 /// converting a string into a string will never result in an error, the appropriate type is `!`.
132 /// (Currently the type actually used is an enum with no variants, though this is only because `!`
133 /// was added to Rust at a later date and it may change in the future). With an [`Err`] type of
134 /// `!`, if we have to call [`String::from_str`] for some reason the result will be a
135 /// [`Result<String, !>`] which we can unpack like this:
136 ///
137 /// ```ignore (string-from-str-error-type-is-not-never-yet)
138 /// #[feature(exhaustive_patterns)]
139 /// // NOTE: This does not work today!
140 /// let Ok(s) = String::from_str("hello");
141 /// ```
142 ///
143 /// Since the [`Err`] variant contains a `!`, it can never occur. If the `exhaustive_patterns`
144 /// feature is present this means we can exhaustively match on [`Result<T, !>`] by just taking the
145 /// [`Ok`] variant. This illustrates another behaviour of `!` - it can be used to "delete" certain
146 /// enum variants from generic types like `Result`.
147 ///
148 /// ## Infinite loops
149 ///
150 /// While [`Result<T, !>`] is very useful for removing errors, `!` can also be used to remove
151 /// successes as well. If we think of [`Result<T, !>`] as "if this function returns, it has not
152 /// errored," we get a very intuitive idea of [`Result<!, E>`] as well: if the function returns, it
153 /// *has* errored.
154 ///
155 /// For example, consider the case of a simple web server, which can be simplified to:
156 ///
157 /// ```ignore (hypothetical-example)
158 /// loop {
159 ///     let (client, request) = get_request().expect("disconnected");
160 ///     let response = request.process();
161 ///     response.send(client);
162 /// }
163 /// ```
164 ///
165 /// Currently, this isn't ideal, because we simply panic whenever we fail to get a new connection.
166 /// Instead, we'd like to keep track of this error, like this:
167 ///
168 /// ```ignore (hypothetical-example)
169 /// loop {
170 ///     match get_request() {
171 ///         Err(err) => break err,
172 ///         Ok((client, request)) => {
173 ///             let response = request.process();
174 ///             response.send(client);
175 ///         },
176 ///     }
177 /// }
178 /// ```
179 ///
180 /// Now, when the server disconnects, we exit the loop with an error instead of panicking. While it
181 /// might be intuitive to simply return the error, we might want to wrap it in a [`Result<!, E>`]
182 /// instead:
183 ///
184 /// ```ignore (hypothetical-example)
185 /// fn server_loop() -> Result<!, ConnectionError> {
186 ///     loop {
187 ///         let (client, request) = get_request()?;
188 ///         let response = request.process();
189 ///         response.send(client);
190 ///     }
191 /// }
192 /// ```
193 ///
194 /// Now, we can use `?` instead of `match`, and the return type makes a lot more sense: if the loop
195 /// ever stops, it means that an error occurred. We don't even have to wrap the loop in an `Ok`
196 /// because `!` coerces to `Result<!, ConnectionError>` automatically.
197 ///
198 /// [`String::from_str`]: str/trait.FromStr.html#tymethod.from_str
199 /// [`Result<String, !>`]: result/enum.Result.html
200 /// [`Result<T, !>`]: result/enum.Result.html
201 /// [`Result<!, E>`]: result/enum.Result.html
202 /// [`Ok`]: result/enum.Result.html#variant.Ok
203 /// [`String`]: string/struct.String.html
204 /// [`Err`]: result/enum.Result.html#variant.Err
205 /// [`FromStr`]: str/trait.FromStr.html
206 ///
207 /// # `!` and traits
208 ///
209 /// When writing your own traits, `!` should have an `impl` whenever there is an obvious `impl`
210 /// which doesn't `panic!`. As it turns out, most traits can have an `impl` for `!`. Take [`Debug`]
211 /// for example:
212 ///
213 /// ```
214 /// #![feature(never_type)]
215 /// # use std::fmt;
216 /// # trait Debug {
217 /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result;
218 /// # }
219 /// impl Debug for ! {
220 ///     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
221 ///         *self
222 ///     }
223 /// }
224 /// ```
225 ///
226 /// Once again we're using `!`'s ability to coerce into any other type, in this case
227 /// [`fmt::Result`]. Since this method takes a `&!` as an argument we know that it can never be
228 /// called (because there is no value of type `!` for it to be called with). Writing `*self`
229 /// essentially tells the compiler "We know that this code can never be run, so just treat the
230 /// entire function body as having type [`fmt::Result`]". This pattern can be used a lot when
231 /// implementing traits for `!`. Generally, any trait which only has methods which take a `self`
232 /// parameter should have such an impl.
233 ///
234 /// On the other hand, one trait which would not be appropriate to implement is [`Default`]:
235 ///
236 /// ```
237 /// trait Default {
238 ///     fn default() -> Self;
239 /// }
240 /// ```
241 ///
242 /// Since `!` has no values, it has no default value either. It's true that we could write an
243 /// `impl` for this which simply panics, but the same is true for any type (we could `impl
244 /// Default` for (eg.) [`File`] by just making [`default()`] panic.)
245 ///
246 /// [`fmt::Result`]: fmt/type.Result.html
247 /// [`File`]: fs/struct.File.html
248 /// [`Debug`]: fmt/trait.Debug.html
249 /// [`Default`]: default/trait.Default.html
250 /// [`default()`]: default/trait.Default.html#tymethod.default
251 ///
252 #[unstable(feature = "never_type", issue = "35121")]
253 mod prim_never { }
254
255 #[doc(primitive = "char")]
256 //
257 /// A character type.
258 ///
259 /// The `char` type represents a single character. More specifically, since
260 /// 'character' isn't a well-defined concept in Unicode, `char` is a '[Unicode
261 /// scalar value]', which is similar to, but not the same as, a '[Unicode code
262 /// point]'.
263 ///
264 /// [Unicode scalar value]: http://www.unicode.org/glossary/#unicode_scalar_value
265 /// [Unicode code point]: http://www.unicode.org/glossary/#code_point
266 ///
267 /// This documentation describes a number of methods and trait implementations on the
268 /// `char` type. For technical reasons, there is additional, separate
269 /// documentation in [the `std::char` module](char/index.html) as well.
270 ///
271 /// # Representation
272 ///
273 /// `char` is always four bytes in size. This is a different representation than
274 /// a given character would have as part of a [`String`]. For example:
275 ///
276 /// ```
277 /// let v = vec!['h', 'e', 'l', 'l', 'o'];
278 ///
279 /// // five elements times four bytes for each element
280 /// assert_eq!(20, v.len() * std::mem::size_of::<char>());
281 ///
282 /// let s = String::from("hello");
283 ///
284 /// // five elements times one byte per element
285 /// assert_eq!(5, s.len() * std::mem::size_of::<u8>());
286 /// ```
287 ///
288 /// [`String`]: string/struct.String.html
289 ///
290 /// As always, remember that a human intuition for 'character' may not map to
291 /// Unicode's definitions. For example, despite looking similar, the 'é'
292 /// character is one Unicode code point while 'é' is two Unicode code points:
293 ///
294 /// ```
295 /// let mut chars = "é".chars();
296 /// // U+00e9: 'latin small letter e with acute'
297 /// assert_eq!(Some('\u{00e9}'), chars.next());
298 /// assert_eq!(None, chars.next());
299 ///
300 /// let mut chars = "é".chars();
301 /// // U+0065: 'latin small letter e'
302 /// assert_eq!(Some('\u{0065}'), chars.next());
303 /// // U+0301: 'combining acute accent'
304 /// assert_eq!(Some('\u{0301}'), chars.next());
305 /// assert_eq!(None, chars.next());
306 /// ```
307 ///
308 /// This means that the contents of the first string above _will_ fit into a
309 /// `char` while the contents of the second string _will not_. Trying to create
310 /// a `char` literal with the contents of the second string gives an error:
311 ///
312 /// ```text
313 /// error: character literal may only contain one codepoint: 'é'
314 /// let c = 'é';
315 ///         ^^^^
316 /// ```
317 ///
318 /// Another implication of the 4-byte fixed size of a `char` is that
319 /// per-`char` processing can end up using a lot more memory:
320 ///
321 /// ```
322 /// let s = String::from("love: ❤️");
323 /// let v: Vec<char> = s.chars().collect();
324 ///
325 /// assert_eq!(12, std::mem::size_of_val(&s[..]));
326 /// assert_eq!(32, std::mem::size_of_val(&v[..]));
327 /// ```
328 #[stable(feature = "rust1", since = "1.0.0")]
329 mod prim_char { }
330
331 #[doc(primitive = "unit")]
332 //
333 /// The `()` type, sometimes called "unit" or "nil".
334 ///
335 /// The `()` type has exactly one value `()`, and is used when there
336 /// is no other meaningful value that could be returned. `()` is most
337 /// commonly seen implicitly: functions without a `-> ...` implicitly
338 /// have return type `()`, that is, these are equivalent:
339 ///
340 /// ```rust
341 /// fn long() -> () {}
342 ///
343 /// fn short() {}
344 /// ```
345 ///
346 /// The semicolon `;` can be used to discard the result of an
347 /// expression at the end of a block, making the expression (and thus
348 /// the block) evaluate to `()`. For example,
349 ///
350 /// ```rust
351 /// fn returns_i64() -> i64 {
352 ///     1i64
353 /// }
354 /// fn returns_unit() {
355 ///     1i64;
356 /// }
357 ///
358 /// let is_i64 = {
359 ///     returns_i64()
360 /// };
361 /// let is_unit = {
362 ///     returns_i64();
363 /// };
364 /// ```
365 ///
366 #[stable(feature = "rust1", since = "1.0.0")]
367 mod prim_unit { }
368
369 #[doc(primitive = "pointer")]
370 //
371 /// Raw, unsafe pointers, `*const T`, and `*mut T`.
372 ///
373 /// *[See also the `std::ptr` module](ptr/index.html).*
374 ///
375 /// Working with raw pointers in Rust is uncommon,
376 /// typically limited to a few patterns.
377 ///
378 /// Use the [`null`] and [`null_mut`] functions to create null pointers, and the
379 /// [`is_null`] method of the `*const T` and `*mut T` types to check for null.
380 /// The `*const T` and `*mut T` types also define the [`offset`] method, for
381 /// pointer math.
382 ///
383 /// # Common ways to create raw pointers
384 ///
385 /// ## 1. Coerce a reference (`&T`) or mutable reference (`&mut T`).
386 ///
387 /// ```
388 /// let my_num: i32 = 10;
389 /// let my_num_ptr: *const i32 = &my_num;
390 /// let mut my_speed: i32 = 88;
391 /// let my_speed_ptr: *mut i32 = &mut my_speed;
392 /// ```
393 ///
394 /// To get a pointer to a boxed value, dereference the box:
395 ///
396 /// ```
397 /// let my_num: Box<i32> = Box::new(10);
398 /// let my_num_ptr: *const i32 = &*my_num;
399 /// let mut my_speed: Box<i32> = Box::new(88);
400 /// let my_speed_ptr: *mut i32 = &mut *my_speed;
401 /// ```
402 ///
403 /// This does not take ownership of the original allocation
404 /// and requires no resource management later,
405 /// but you must not use the pointer after its lifetime.
406 ///
407 /// ## 2. Consume a box (`Box<T>`).
408 ///
409 /// The [`into_raw`] function consumes a box and returns
410 /// the raw pointer. It doesn't destroy `T` or deallocate any memory.
411 ///
412 /// ```
413 /// let my_speed: Box<i32> = Box::new(88);
414 /// let my_speed: *mut i32 = Box::into_raw(my_speed);
415 ///
416 /// // By taking ownership of the original `Box<T>` though
417 /// // we are obligated to put it together later to be destroyed.
418 /// unsafe {
419 ///     drop(Box::from_raw(my_speed));
420 /// }
421 /// ```
422 ///
423 /// Note that here the call to [`drop`] is for clarity - it indicates
424 /// that we are done with the given value and it should be destroyed.
425 ///
426 /// ## 3. Get it from C.
427 ///
428 /// ```
429 /// # #![feature(libc)]
430 /// extern crate libc;
431 ///
432 /// use std::mem;
433 ///
434 /// fn main() {
435 ///     unsafe {
436 ///         let my_num: *mut i32 = libc::malloc(mem::size_of::<i32>()) as *mut i32;
437 ///         if my_num.is_null() {
438 ///             panic!("failed to allocate memory");
439 ///         }
440 ///         libc::free(my_num as *mut libc::c_void);
441 ///     }
442 /// }
443 /// ```
444 ///
445 /// Usually you wouldn't literally use `malloc` and `free` from Rust,
446 /// but C APIs hand out a lot of pointers generally, so are a common source
447 /// of raw pointers in Rust.
448 ///
449 /// [`null`]: ../std/ptr/fn.null.html
450 /// [`null_mut`]: ../std/ptr/fn.null_mut.html
451 /// [`is_null`]: ../std/primitive.pointer.html#method.is_null
452 /// [`offset`]: ../std/primitive.pointer.html#method.offset
453 /// [`into_raw`]: ../std/boxed/struct.Box.html#method.into_raw
454 /// [`drop`]: ../std/mem/fn.drop.html
455 #[stable(feature = "rust1", since = "1.0.0")]
456 mod prim_pointer { }
457
458 #[doc(primitive = "array")]
459 //
460 /// A fixed-size array, denoted `[T; N]`, for the element type, `T`, and the
461 /// non-negative compile-time constant size, `N`.
462 ///
463 /// There are two syntactic forms for creating an array:
464 ///
465 /// * A list with each element, i.e., `[x, y, z]`.
466 /// * A repeat expression `[x; N]`, which produces an array with `N` copies of `x`.
467 ///   The type of `x` must be [`Copy`][copy].
468 ///
469 /// Arrays of sizes from 0 to 32 (inclusive) implement the following traits if
470 /// the element type allows it:
471 ///
472 /// - [`Debug`][debug]
473 /// - [`IntoIterator`][intoiterator] (implemented for `&[T; N]` and `&mut [T; N]`)
474 /// - [`PartialEq`][partialeq], [`PartialOrd`][partialord], [`Eq`][eq], [`Ord`][ord]
475 /// - [`Hash`][hash]
476 /// - [`AsRef`][asref], [`AsMut`][asmut]
477 /// - [`Borrow`][borrow], [`BorrowMut`][borrowmut]
478 /// - [`Default`][default]
479 ///
480 /// This limitation on the size `N` exists because Rust does not yet support
481 /// code that is generic over the size of an array type. `[Foo; 3]` and `[Bar; 3]`
482 /// are instances of same generic type `[T; 3]`, but `[Foo; 3]` and `[Foo; 5]` are
483 /// entirely different types. As a stopgap, trait implementations are
484 /// statically generated up to size 32.
485 ///
486 /// Arrays of *any* size are [`Copy`][copy] if the element type is [`Copy`][copy]
487 /// and [`Clone`][clone] if the element type is [`Clone`][clone]. This works
488 /// because [`Copy`][copy] and [`Clone`][clone] traits are specially known
489 /// to the compiler.
490 ///
491 /// Arrays coerce to [slices (`[T]`)][slice], so a slice method may be called on
492 /// an array. Indeed, this provides most of the API for working with arrays.
493 /// Slices have a dynamic size and do not coerce to arrays.
494 ///
495 /// There is no way to move elements out of an array. See [`mem::replace`][replace]
496 /// for an alternative.
497 ///
498 /// # Examples
499 ///
500 /// ```
501 /// let mut array: [i32; 3] = [0; 3];
502 ///
503 /// array[1] = 1;
504 /// array[2] = 2;
505 ///
506 /// assert_eq!([1, 2], &array[1..]);
507 ///
508 /// // This loop prints: 0 1 2
509 /// for x in &array {
510 ///     print!("{} ", x);
511 /// }
512 /// ```
513 ///
514 /// An array itself is not iterable:
515 ///
516 /// ```compile_fail,E0277
517 /// let array: [i32; 3] = [0; 3];
518 ///
519 /// for x in array { }
520 /// // error: the trait bound `[i32; 3]: std::iter::Iterator` is not satisfied
521 /// ```
522 ///
523 /// The solution is to coerce the array to a slice by calling a slice method:
524 ///
525 /// ```
526 /// # let array: [i32; 3] = [0; 3];
527 /// for x in array.iter() { }
528 /// ```
529 ///
530 /// If the array has 32 or fewer elements (see above), you can also use the
531 /// array reference's [`IntoIterator`] implementation:
532 ///
533 /// ```
534 /// # let array: [i32; 3] = [0; 3];
535 /// for x in &array { }
536 /// ```
537 ///
538 /// [slice]: primitive.slice.html
539 /// [copy]: marker/trait.Copy.html
540 /// [clone]: clone/trait.Clone.html
541 /// [debug]: fmt/trait.Debug.html
542 /// [intoiterator]: iter/trait.IntoIterator.html
543 /// [partialeq]: cmp/trait.PartialEq.html
544 /// [partialord]: cmp/trait.PartialOrd.html
545 /// [eq]: cmp/trait.Eq.html
546 /// [ord]: cmp/trait.Ord.html
547 /// [hash]: hash/trait.Hash.html
548 /// [asref]: convert/trait.AsRef.html
549 /// [asmut]: convert/trait.AsMut.html
550 /// [borrow]: borrow/trait.Borrow.html
551 /// [borrowmut]: borrow/trait.BorrowMut.html
552 /// [default]: default/trait.Default.html
553 /// [replace]: mem/fn.replace.html
554 /// [`IntoIterator`]: iter/trait.IntoIterator.html
555 ///
556 #[stable(feature = "rust1", since = "1.0.0")]
557 mod prim_array { }
558
559 #[doc(primitive = "slice")]
560 #[doc(alias = "[")]
561 #[doc(alias = "]")]
562 #[doc(alias = "[]")]
563 //
564 /// A dynamically-sized view into a contiguous sequence, `[T]`.
565 ///
566 /// *[See also the `std::slice` module](slice/index.html).*
567 ///
568 /// Slices are a view into a block of memory represented as a pointer and a
569 /// length.
570 ///
571 /// ```
572 /// // slicing a Vec
573 /// let vec = vec![1, 2, 3];
574 /// let int_slice = &vec[..];
575 /// // coercing an array to a slice
576 /// let str_slice: &[&str] = &["one", "two", "three"];
577 /// ```
578 ///
579 /// Slices are either mutable or shared. The shared slice type is `&[T]`,
580 /// while the mutable slice type is `&mut [T]`, where `T` represents the element
581 /// type. For example, you can mutate the block of memory that a mutable slice
582 /// points to:
583 ///
584 /// ```
585 /// let x = &mut [1, 2, 3];
586 /// x[1] = 7;
587 /// assert_eq!(x, &[1, 7, 3]);
588 /// ```
589 ///
590 #[stable(feature = "rust1", since = "1.0.0")]
591 mod prim_slice { }
592
593 #[doc(primitive = "str")]
594 //
595 /// String slices.
596 ///
597 /// *[See also the `std::str` module](str/index.html).*
598 ///
599 /// The `str` type, also called a 'string slice', is the most primitive string
600 /// type. It is usually seen in its borrowed form, `&str`. It is also the type
601 /// of string literals, `&'static str`.
602 ///
603 /// String slices are always valid UTF-8.
604 ///
605 /// # Examples
606 ///
607 /// String literals are string slices:
608 ///
609 /// ```
610 /// let hello = "Hello, world!";
611 ///
612 /// // with an explicit type annotation
613 /// let hello: &'static str = "Hello, world!";
614 /// ```
615 ///
616 /// They are `'static` because they're stored directly in the final binary, and
617 /// so will be valid for the `'static` duration.
618 ///
619 /// # Representation
620 ///
621 /// A `&str` is made up of two components: a pointer to some bytes, and a
622 /// length. You can look at these with the [`as_ptr`] and [`len`] methods:
623 ///
624 /// ```
625 /// use std::slice;
626 /// use std::str;
627 ///
628 /// let story = "Once upon a time...";
629 ///
630 /// let ptr = story.as_ptr();
631 /// let len = story.len();
632 ///
633 /// // story has nineteen bytes
634 /// assert_eq!(19, len);
635 ///
636 /// // We can re-build a str out of ptr and len. This is all unsafe because
637 /// // we are responsible for making sure the two components are valid:
638 /// let s = unsafe {
639 ///     // First, we build a &[u8]...
640 ///     let slice = slice::from_raw_parts(ptr, len);
641 ///
642 ///     // ... and then convert that slice into a string slice
643 ///     str::from_utf8(slice)
644 /// };
645 ///
646 /// assert_eq!(s, Ok(story));
647 /// ```
648 ///
649 /// [`as_ptr`]: #method.as_ptr
650 /// [`len`]: #method.len
651 ///
652 /// Note: This example shows the internals of `&str`. `unsafe` should not be
653 /// used to get a string slice under normal circumstances. Use `as_slice`
654 /// instead.
655 #[stable(feature = "rust1", since = "1.0.0")]
656 mod prim_str { }
657
658 #[doc(primitive = "tuple")]
659 #[doc(alias = "(")]
660 #[doc(alias = ")")]
661 #[doc(alias = "()")]
662 //
663 /// A finite heterogeneous sequence, `(T, U, ..)`.
664 ///
665 /// Let's cover each of those in turn:
666 ///
667 /// Tuples are *finite*. In other words, a tuple has a length. Here's a tuple
668 /// of length `3`:
669 ///
670 /// ```
671 /// ("hello", 5, 'c');
672 /// ```
673 ///
674 /// 'Length' is also sometimes called 'arity' here; each tuple of a different
675 /// length is a different, distinct type.
676 ///
677 /// Tuples are *heterogeneous*. This means that each element of the tuple can
678 /// have a different type. In that tuple above, it has the type:
679 ///
680 /// ```
681 /// # let _:
682 /// (&'static str, i32, char)
683 /// # = ("hello", 5, 'c');
684 /// ```
685 ///
686 /// Tuples are a *sequence*. This means that they can be accessed by position;
687 /// this is called 'tuple indexing', and it looks like this:
688 ///
689 /// ```rust
690 /// let tuple = ("hello", 5, 'c');
691 ///
692 /// assert_eq!(tuple.0, "hello");
693 /// assert_eq!(tuple.1, 5);
694 /// assert_eq!(tuple.2, 'c');
695 /// ```
696 ///
697 /// For more about tuples, see [the book](../book/ch03-02-data-types.html#the-tuple-type).
698 ///
699 /// # Trait implementations
700 ///
701 /// If every type inside a tuple implements one of the following traits, then a
702 /// tuple itself also implements it.
703 ///
704 /// * [`Clone`]
705 /// * [`Copy`]
706 /// * [`PartialEq`]
707 /// * [`Eq`]
708 /// * [`PartialOrd`]
709 /// * [`Ord`]
710 /// * [`Debug`]
711 /// * [`Default`]
712 /// * [`Hash`]
713 ///
714 /// [`Clone`]: clone/trait.Clone.html
715 /// [`Copy`]: marker/trait.Copy.html
716 /// [`PartialEq`]: cmp/trait.PartialEq.html
717 /// [`Eq`]: cmp/trait.Eq.html
718 /// [`PartialOrd`]: cmp/trait.PartialOrd.html
719 /// [`Ord`]: cmp/trait.Ord.html
720 /// [`Debug`]: fmt/trait.Debug.html
721 /// [`Default`]: default/trait.Default.html
722 /// [`Hash`]: hash/trait.Hash.html
723 ///
724 /// Due to a temporary restriction in Rust's type system, these traits are only
725 /// implemented on tuples of arity 12 or less. In the future, this may change.
726 ///
727 /// # Examples
728 ///
729 /// Basic usage:
730 ///
731 /// ```
732 /// let tuple = ("hello", 5, 'c');
733 ///
734 /// assert_eq!(tuple.0, "hello");
735 /// ```
736 ///
737 /// Tuples are often used as a return type when you want to return more than
738 /// one value:
739 ///
740 /// ```
741 /// fn calculate_point() -> (i32, i32) {
742 ///     // Don't do a calculation, that's not the point of the example
743 ///     (4, 5)
744 /// }
745 ///
746 /// let point = calculate_point();
747 ///
748 /// assert_eq!(point.0, 4);
749 /// assert_eq!(point.1, 5);
750 ///
751 /// // Combining this with patterns can be nicer.
752 ///
753 /// let (x, y) = calculate_point();
754 ///
755 /// assert_eq!(x, 4);
756 /// assert_eq!(y, 5);
757 /// ```
758 ///
759 #[stable(feature = "rust1", since = "1.0.0")]
760 mod prim_tuple { }
761
762 #[doc(primitive = "f32")]
763 /// The 32-bit floating point type.
764 ///
765 /// *[See also the `std::f32` module](f32/index.html).*
766 ///
767 #[stable(feature = "rust1", since = "1.0.0")]
768 mod prim_f32 { }
769
770 #[doc(primitive = "f64")]
771 //
772 /// The 64-bit floating point type.
773 ///
774 /// *[See also the `std::f64` module](f64/index.html).*
775 ///
776 #[stable(feature = "rust1", since = "1.0.0")]
777 mod prim_f64 { }
778
779 #[doc(primitive = "i8")]
780 //
781 /// The 8-bit signed integer type.
782 ///
783 /// *[See also the `std::i8` module](i8/index.html).*
784 #[stable(feature = "rust1", since = "1.0.0")]
785 mod prim_i8 { }
786
787 #[doc(primitive = "i16")]
788 //
789 /// The 16-bit signed integer type.
790 ///
791 /// *[See also the `std::i16` module](i16/index.html).*
792 #[stable(feature = "rust1", since = "1.0.0")]
793 mod prim_i16 { }
794
795 #[doc(primitive = "i32")]
796 //
797 /// The 32-bit signed integer type.
798 ///
799 /// *[See also the `std::i32` module](i32/index.html).*
800 #[stable(feature = "rust1", since = "1.0.0")]
801 mod prim_i32 { }
802
803 #[doc(primitive = "i64")]
804 //
805 /// The 64-bit signed integer type.
806 ///
807 /// *[See also the `std::i64` module](i64/index.html).*
808 #[stable(feature = "rust1", since = "1.0.0")]
809 mod prim_i64 { }
810
811 #[doc(primitive = "i128")]
812 //
813 /// The 128-bit signed integer type.
814 ///
815 /// *[See also the `std::i128` module](i128/index.html).*
816 #[stable(feature = "i128", since="1.26.0")]
817 mod prim_i128 { }
818
819 #[doc(primitive = "u8")]
820 //
821 /// The 8-bit unsigned integer type.
822 ///
823 /// *[See also the `std::u8` module](u8/index.html).*
824 #[stable(feature = "rust1", since = "1.0.0")]
825 mod prim_u8 { }
826
827 #[doc(primitive = "u16")]
828 //
829 /// The 16-bit unsigned integer type.
830 ///
831 /// *[See also the `std::u16` module](u16/index.html).*
832 #[stable(feature = "rust1", since = "1.0.0")]
833 mod prim_u16 { }
834
835 #[doc(primitive = "u32")]
836 //
837 /// The 32-bit unsigned integer type.
838 ///
839 /// *[See also the `std::u32` module](u32/index.html).*
840 #[stable(feature = "rust1", since = "1.0.0")]
841 mod prim_u32 { }
842
843 #[doc(primitive = "u64")]
844 //
845 /// The 64-bit unsigned integer type.
846 ///
847 /// *[See also the `std::u64` module](u64/index.html).*
848 #[stable(feature = "rust1", since = "1.0.0")]
849 mod prim_u64 { }
850
851 #[doc(primitive = "u128")]
852 //
853 /// The 128-bit unsigned integer type.
854 ///
855 /// *[See also the `std::u128` module](u128/index.html).*
856 #[stable(feature = "i128", since="1.26.0")]
857 mod prim_u128 { }
858
859 #[doc(primitive = "isize")]
860 //
861 /// The pointer-sized signed integer type.
862 ///
863 /// *[See also the `std::isize` module](isize/index.html).*
864 ///
865 /// The size of this primitive is how many bytes it takes to reference any
866 /// location in memory. For example, on a 32 bit target, this is 4 bytes
867 /// and on a 64 bit target, this is 8 bytes.
868 #[stable(feature = "rust1", since = "1.0.0")]
869 mod prim_isize { }
870
871 #[doc(primitive = "usize")]
872 //
873 /// The pointer-sized unsigned integer type.
874 ///
875 /// *[See also the `std::usize` module](usize/index.html).*
876 ///
877 /// The size of this primitive is how many bytes it takes to reference any
878 /// location in memory. For example, on a 32 bit target, this is 4 bytes
879 /// and on a 64 bit target, this is 8 bytes.
880 #[stable(feature = "rust1", since = "1.0.0")]
881 mod prim_usize { }
882
883 #[doc(primitive = "reference")]
884 #[doc(alias = "&")]
885 //
886 /// References, both shared and mutable.
887 ///
888 /// A reference represents a borrow of some owned value. You can get one by using the `&` or `&mut`
889 /// operators on a value, or by using a `ref` or `ref mut` pattern.
890 ///
891 /// For those familiar with pointers, a reference is just a pointer that is assumed to not be null.
892 /// In fact, `Option<&T>` has the same memory representation as a nullable pointer, and can be
893 /// passed across FFI boundaries as such.
894 ///
895 /// In most cases, references can be used much like the original value. Field access, method
896 /// calling, and indexing work the same (save for mutability rules, of course). In addition, the
897 /// comparison operators transparently defer to the referent's implementation, allowing references
898 /// to be compared the same as owned values.
899 ///
900 /// References have a lifetime attached to them, which represents the scope for which the borrow is
901 /// valid. A lifetime is said to "outlive" another one if its representative scope is as long or
902 /// longer than the other. The `'static` lifetime is the longest lifetime, which represents the
903 /// total life of the program. For example, string literals have a `'static` lifetime because the
904 /// text data is embedded into the binary of the program, rather than in an allocation that needs
905 /// to be dynamically managed.
906 ///
907 /// `&mut T` references can be freely coerced into `&T` references with the same referent type, and
908 /// references with longer lifetimes can be freely coerced into references with shorter ones.
909 ///
910 /// Reference equality by address, instead of comparing the values pointed to, is accomplished via
911 /// implicit reference-pointer coercion and raw pointer equality via [`ptr::eq`], while
912 /// [`PartialEq`] compares values.
913 ///
914 /// [`ptr::eq`]: ptr/fn.eq.html
915 /// [`PartialEq`]: cmp/trait.PartialEq.html
916 ///
917 /// ```
918 /// use std::ptr;
919 ///
920 /// let five = 5;
921 /// let other_five = 5;
922 /// let five_ref = &five;
923 /// let same_five_ref = &five;
924 /// let other_five_ref = &other_five;
925 ///
926 /// assert!(five_ref == same_five_ref);
927 /// assert!(five_ref == other_five_ref);
928 ///
929 /// assert!(ptr::eq(five_ref, same_five_ref));
930 /// assert!(!ptr::eq(five_ref, other_five_ref));
931 /// ```
932 ///
933 /// For more information on how to use references, see [the book's section on "References and
934 /// Borrowing"][book-refs].
935 ///
936 /// [book-refs]: ../book/second-edition/ch04-02-references-and-borrowing.html
937 ///
938 /// # Trait implementations
939 ///
940 /// The following traits are implemented for all `&T`, regardless of the type of its referent:
941 ///
942 /// * [`Copy`]
943 /// * [`Clone`] \(Note that this will not defer to `T`'s `Clone` implementation if it exists!)
944 /// * [`Deref`]
945 /// * [`Borrow`]
946 /// * [`Pointer`]
947 ///
948 /// [`Copy`]: marker/trait.Copy.html
949 /// [`Clone`]: clone/trait.Clone.html
950 /// [`Deref`]: ops/trait.Deref.html
951 /// [`Borrow`]: borrow/trait.Borrow.html
952 /// [`Pointer`]: fmt/trait.Pointer.html
953 ///
954 /// `&mut T` references get all of the above except `Copy` and `Clone` (to prevent creating
955 /// multiple simultaneous mutable borrows), plus the following, regardless of the type of its
956 /// referent:
957 ///
958 /// * [`DerefMut`]
959 /// * [`BorrowMut`]
960 ///
961 /// [`DerefMut`]: ops/trait.DerefMut.html
962 /// [`BorrowMut`]: borrow/trait.BorrowMut.html
963 ///
964 /// The following traits are implemented on `&T` references if the underlying `T` also implements
965 /// that trait:
966 ///
967 /// * All the traits in [`std::fmt`] except [`Pointer`] and [`fmt::Write`]
968 /// * [`PartialOrd`]
969 /// * [`Ord`]
970 /// * [`PartialEq`]
971 /// * [`Eq`]
972 /// * [`AsRef`]
973 /// * [`Fn`] \(in addition, `&T` references get [`FnMut`] and [`FnOnce`] if `T: Fn`)
974 /// * [`Hash`]
975 /// * [`ToSocketAddrs`]
976 ///
977 /// [`std::fmt`]: fmt/index.html
978 /// [`fmt::Write`]: fmt/trait.Write.html
979 /// [`PartialOrd`]: cmp/trait.PartialOrd.html
980 /// [`Ord`]: cmp/trait.Ord.html
981 /// [`PartialEq`]: cmp/trait.PartialEq.html
982 /// [`Eq`]: cmp/trait.Eq.html
983 /// [`AsRef`]: convert/trait.AsRef.html
984 /// [`Fn`]: ops/trait.Fn.html
985 /// [`FnMut`]: ops/trait.FnMut.html
986 /// [`FnOnce`]: ops/trait.FnOnce.html
987 /// [`Hash`]: hash/trait.Hash.html
988 /// [`ToSocketAddrs`]: net/trait.ToSocketAddrs.html
989 ///
990 /// `&mut T` references get all of the above except `ToSocketAddrs`, plus the following, if `T`
991 /// implements that trait:
992 ///
993 /// * [`AsMut`]
994 /// * [`FnMut`] \(in addition, `&mut T` references get [`FnOnce`] if `T: FnMut`)
995 /// * [`fmt::Write`]
996 /// * [`Iterator`]
997 /// * [`DoubleEndedIterator`]
998 /// * [`ExactSizeIterator`]
999 /// * [`FusedIterator`]
1000 /// * [`TrustedLen`]
1001 /// * [`Send`] \(note that `&T` references only get `Send` if `T: Sync`)
1002 /// * [`io::Write`]
1003 /// * [`Read`]
1004 /// * [`Seek`]
1005 /// * [`BufRead`]
1006 ///
1007 /// [`AsMut`]: convert/trait.AsMut.html
1008 /// [`Iterator`]: iter/trait.Iterator.html
1009 /// [`DoubleEndedIterator`]: iter/trait.DoubleEndedIterator.html
1010 /// [`ExactSizeIterator`]: iter/trait.ExactSizeIterator.html
1011 /// [`FusedIterator`]: iter/trait.FusedIterator.html
1012 /// [`TrustedLen`]: iter/trait.TrustedLen.html
1013 /// [`Send`]: marker/trait.Send.html
1014 /// [`io::Write`]: io/trait.Write.html
1015 /// [`Read`]: io/trait.Read.html
1016 /// [`Seek`]: io/trait.Seek.html
1017 /// [`BufRead`]: io/trait.BufRead.html
1018 ///
1019 /// Note that due to method call deref coercion, simply calling a trait method will act like they
1020 /// work on references as well as they do on owned values! The implementations described here are
1021 /// meant for generic contexts, where the final type `T` is a type parameter or otherwise not
1022 /// locally known.
1023 #[stable(feature = "rust1", since = "1.0.0")]
1024 mod prim_ref { }
1025
1026 #[doc(primitive = "fn")]
1027 //
1028 /// Function pointers, like `fn(usize) -> bool`.
1029 ///
1030 /// *See also the traits [`Fn`], [`FnMut`], and [`FnOnce`].*
1031 ///
1032 /// [`Fn`]: ops/trait.Fn.html
1033 /// [`FnMut`]: ops/trait.FnMut.html
1034 /// [`FnOnce`]: ops/trait.FnOnce.html
1035 ///
1036 /// Plain function pointers are obtained by casting either plain functions, or closures that don't
1037 /// capture an environment:
1038 ///
1039 /// ```
1040 /// fn add_one(x: usize) -> usize {
1041 ///     x + 1
1042 /// }
1043 ///
1044 /// let ptr: fn(usize) -> usize = add_one;
1045 /// assert_eq!(ptr(5), 6);
1046 ///
1047 /// let clos: fn(usize) -> usize = |x| x + 5;
1048 /// assert_eq!(clos(5), 10);
1049 /// ```
1050 ///
1051 /// In addition to varying based on their signature, function pointers come in two flavors: safe
1052 /// and unsafe. Plain `fn()` function pointers can only point to safe functions,
1053 /// while `unsafe fn()` function pointers can point to safe or unsafe functions.
1054 ///
1055 /// ```
1056 /// fn add_one(x: usize) -> usize {
1057 ///     x + 1
1058 /// }
1059 ///
1060 /// unsafe fn add_one_unsafely(x: usize) -> usize {
1061 ///     x + 1
1062 /// }
1063 ///
1064 /// let safe_ptr: fn(usize) -> usize = add_one;
1065 ///
1066 /// //ERROR: mismatched types: expected normal fn, found unsafe fn
1067 /// //let bad_ptr: fn(usize) -> usize = add_one_unsafely;
1068 ///
1069 /// let unsafe_ptr: unsafe fn(usize) -> usize = add_one_unsafely;
1070 /// let really_safe_ptr: unsafe fn(usize) -> usize = add_one;
1071 /// ```
1072 ///
1073 /// On top of that, function pointers can vary based on what ABI they use. This is achieved by
1074 /// adding the `extern` keyword to the type name, followed by the ABI in question. For example,
1075 /// `fn()` is different from `extern "C" fn()`, which itself is different from `extern "stdcall"
1076 /// fn()`, and so on for the various ABIs that Rust supports.  Non-`extern` functions have an ABI
1077 /// of `"Rust"`, and `extern` functions without an explicit ABI have an ABI of `"C"`. For more
1078 /// information, see [the nomicon's section on foreign calling conventions][nomicon-abi].
1079 ///
1080 /// [nomicon-abi]: ../nomicon/ffi.html#foreign-calling-conventions
1081 ///
1082 /// Extern function declarations with the "C" or "cdecl" ABIs can also be *variadic*, allowing them
1083 /// to be called with a variable number of arguments. Normal rust functions, even those with an
1084 /// `extern "ABI"`, cannot be variadic. For more information, see [the nomicon's section on
1085 /// variadic functions][nomicon-variadic].
1086 ///
1087 /// [nomicon-variadic]: ../nomicon/ffi.html#variadic-functions
1088 ///
1089 /// These markers can be combined, so `unsafe extern "stdcall" fn()` is a valid type.
1090 ///
1091 /// Like references in rust, function pointers are assumed to not be null, so if you want to pass a
1092 /// function pointer over FFI and be able to accommodate null pointers, make your type
1093 /// `Option<fn()>` with your required signature.
1094 ///
1095 /// Function pointers implement the following traits:
1096 ///
1097 /// * [`Clone`]
1098 /// * [`PartialEq`]
1099 /// * [`Eq`]
1100 /// * [`PartialOrd`]
1101 /// * [`Ord`]
1102 /// * [`Hash`]
1103 /// * [`Pointer`]
1104 /// * [`Debug`]
1105 ///
1106 /// [`Clone`]: clone/trait.Clone.html
1107 /// [`PartialEq`]: cmp/trait.PartialEq.html
1108 /// [`Eq`]: cmp/trait.Eq.html
1109 /// [`PartialOrd`]: cmp/trait.PartialOrd.html
1110 /// [`Ord`]: cmp/trait.Ord.html
1111 /// [`Hash`]: hash/trait.Hash.html
1112 /// [`Pointer`]: fmt/trait.Pointer.html
1113 /// [`Debug`]: fmt/trait.Debug.html
1114 ///
1115 /// Due to a temporary restriction in Rust's type system, these traits are only implemented on
1116 /// functions that take 12 arguments or less, with the `"Rust"` and `"C"` ABIs. In the future, this
1117 /// may change.
1118 ///
1119 /// In addition, function pointers of *any* signature, ABI, or safety are [`Copy`], and all *safe*
1120 /// function pointers implement [`Fn`], [`FnMut`], and [`FnOnce`]. This works because these traits
1121 /// are specially known to the compiler.
1122 ///
1123 /// [`Copy`]: marker/trait.Copy.html
1124 #[stable(feature = "rust1", since = "1.0.0")]
1125 mod prim_fn { }