]> git.lizzy.rs Git - rust.git/blob - src/libstd/primitive_docs.rs
Rollup merge of #31031 - brson:issue-30123, r=nikomatsakis
[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 //
13 /// The boolean type.
14 ///
15 mod prim_bool { }
16
17 #[doc(primitive = "char")]
18 //
19 /// A character type.
20 ///
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
24 /// point]'.
25 ///
26 /// [Unicode scalar value]: http://www.unicode.org/glossary/#unicode_scalar_value
27 /// [Unicode code point]: http://www.unicode.org/glossary/#code_point
28 ///
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.
32 ///
33 /// # Representation
34 ///
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:
37 ///
38 /// ```
39 /// let v = vec!['h', 'e', 'l', 'l', 'o'];
40 ///
41 /// // five elements times four bytes for each element
42 /// assert_eq!(20, v.len() * std::mem::size_of::<char>());
43 ///
44 /// let s = String::from("hello");
45 ///
46 /// // five elements times one byte per element
47 /// assert_eq!(5, s.len() * std::mem::size_of::<u8>());
48 /// ```
49 ///
50 /// [`String`]: string/struct.String.html
51 ///
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:
55 ///
56 /// ```
57 /// let s = String::from("❤️");
58 ///
59 /// // six bytes times one byte for each element
60 /// assert_eq!(6, s.len() * std::mem::size_of::<u8>());
61 /// ```
62 ///
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:
65 ///
66 /// ```text
67 /// error: character literal may only contain one codepoint: '❤
68 /// let heart = '❤️';
69 ///             ^~
70 /// ```
71 ///
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:
74 ///
75 /// ```
76 /// let s = String::from("love: ❤️");
77 /// let v: Vec<char> = s.chars().collect();
78 ///
79 /// assert_eq!(12, s.len() * std::mem::size_of::<u8>());
80 /// assert_eq!(32, v.len() * std::mem::size_of::<char>());
81 /// ```
82 ///
83 /// Or may give you results you may not expect:
84 ///
85 /// ```
86 /// let s = String::from("❤️");
87 ///
88 /// let mut iter = s.chars();
89 ///
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());
94 /// ```
95 mod prim_char { }
96
97 #[doc(primitive = "unit")]
98 //
99 /// The `()` type, sometimes called "unit" or "nil".
100 ///
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:
105 ///
106 /// ```rust
107 /// fn long() -> () {}
108 ///
109 /// fn short() {}
110 /// ```
111 ///
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,
115 ///
116 /// ```rust
117 /// fn returns_i64() -> i64 {
118 ///     1i64
119 /// }
120 /// fn returns_unit() {
121 ///     1i64;
122 /// }
123 ///
124 /// let is_i64 = {
125 ///     returns_i64()
126 /// };
127 /// let is_unit = {
128 ///     returns_i64();
129 /// };
130 /// ```
131 ///
132 mod prim_unit { }
133
134 #[doc(primitive = "pointer")]
135 //
136 /// Raw, unsafe pointers, `*const T`, and `*mut T`.
137 ///
138 /// Working with raw pointers in Rust is uncommon,
139 /// typically limited to a few patterns.
140 ///
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.
144 ///
145 /// # Common ways to create raw pointers
146 ///
147 /// ## 1. Coerce a reference (`&T`) or mutable reference (`&mut T`).
148 ///
149 /// ```
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;
154 /// ```
155 ///
156 /// To get a pointer to a boxed value, dereference the box:
157 ///
158 /// ```
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;
163 /// ```
164 ///
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.
168 ///
169 /// ## 2. Consume a box (`Box<T>`).
170 ///
171 /// The `into_raw` function consumes a box and returns
172 /// the raw pointer. It doesn't destroy `T` or deallocate any memory.
173 ///
174 /// ```
175 /// let my_speed: Box<i32> = Box::new(88);
176 /// let my_speed: *mut i32 = Box::into_raw(my_speed);
177 ///
178 /// // By taking ownership of the original `Box<T>` though
179 /// // we are obligated to put it together later to be destroyed.
180 /// unsafe {
181 ///     drop(Box::from_raw(my_speed));
182 /// }
183 /// ```
184 ///
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.
187 ///
188 /// ## 3. Get it from C.
189 ///
190 /// ```
191 /// # #![feature(libc)]
192 /// extern crate libc;
193 ///
194 /// use std::mem;
195 ///
196 /// fn main() {
197 ///     unsafe {
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");
201 ///         }
202 ///         libc::free(my_num as *mut libc::c_void);
203 ///     }
204 /// }
205 /// ```
206 ///
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.
210 ///
211 /// *[See also the `std::ptr` module](ptr/index.html).*
212 ///
213 mod prim_pointer { }
214
215 #[doc(primitive = "array")]
216 //
217 /// A fixed-size array, denoted `[T; N]`, for the element type, `T`, and the
218 /// non-negative compile time constant size, `N`.
219 ///
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`.
223 ///
224 /// The type `[T; N]` is `Copy` if `T: Copy`.
225 ///
226 /// Arrays of sizes from 0 to 32 (inclusive) implement the following traits if
227 /// the element type allows it:
228 ///
229 /// - `Clone` (only if `T: Copy`)
230 /// - `Debug`
231 /// - `IntoIterator` (implemented for `&[T; N]` and `&mut [T; N]`)
232 /// - `PartialEq`, `PartialOrd`, `Ord`, `Eq`
233 /// - `Hash`
234 /// - `AsRef`, `AsMut`
235 /// - `Borrow`, `BorrowMut`
236 /// - `Default`
237 ///
238 /// Arrays coerce to [slices (`[T]`)][slice], so their methods can be called on
239 /// arrays.
240 ///
241 /// [slice]: primitive.slice.html
242 ///
243 /// Rust does not currently support generics over the size of an array type.
244 ///
245 /// # Examples
246 ///
247 /// ```
248 /// let mut array: [i32; 3] = [0; 3];
249 ///
250 /// array[1] = 1;
251 /// array[2] = 2;
252 ///
253 /// assert_eq!([1, 2], &array[1..]);
254 ///
255 /// // This loop prints: 0 1 2
256 /// for x in &array {
257 ///     print!("{} ", x);
258 /// }
259 ///
260 /// ```
261 ///
262 mod prim_array { }
263
264 #[doc(primitive = "slice")]
265 //
266 /// A dynamically-sized view into a contiguous sequence, `[T]`.
267 ///
268 /// Slices are a view into a block of memory represented as a pointer and a
269 /// length.
270 ///
271 /// ```
272 /// // slicing a Vec
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"];
277 /// ```
278 ///
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
282 /// points to:
283 ///
284 /// ```
285 /// let x = &mut [1, 2, 3];
286 /// x[1] = 7;
287 /// assert_eq!(x, &[1, 7, 3]);
288 /// ```
289 ///
290 /// *[See also the `std::slice` module](slice/index.html).*
291 ///
292 mod prim_slice { }
293
294 #[doc(primitive = "str")]
295 //
296 /// String slices.
297 ///
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`.
301 ///
302 /// Strings slices are always valid UTF-8.
303 ///
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.
307 ///
308 /// # Examples
309 ///
310 /// String literals are string slices:
311 ///
312 /// ```
313 /// let hello = "Hello, world!";
314 ///
315 /// // with an explicit type annotation
316 /// let hello: &'static str = "Hello, world!";
317 /// ```
318 ///
319 /// They are `'static` because they're stored directly in the final binary, and
320 /// so will be valid for the `'static` duration.
321 ///
322 /// # Representation
323 ///
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:
326 ///
327 /// ```
328 /// use std::slice;
329 /// use std::str;
330 ///
331 /// let story = "Once upon a time...";
332 ///
333 /// let ptr = story.as_ptr();
334 /// let len = story.len();
335 ///
336 /// // story has nineteen bytes
337 /// assert_eq!(19, len);
338 ///
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:
341 /// let s = unsafe {
342 ///     // First, we build a &[u8]...
343 ///     let slice = slice::from_raw_parts(ptr, len);
344 ///
345 ///     // ... and then convert that slice into a string slice
346 ///     str::from_utf8(slice)
347 /// };
348 ///
349 /// assert_eq!(s, Ok(story));
350 /// ```
351 ///
352 /// [`.as_ptr()`]: #method.as_ptr
353 /// [`len()`]: #method.len
354 mod prim_str { }
355
356 #[doc(primitive = "tuple")]
357 //
358 /// A finite heterogeneous sequence, `(T, U, ..)`.
359 ///
360 /// To access the _N_-th element of a tuple one can use `N` itself
361 /// as a field of the tuple.
362 ///
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`.
366 ///
367 /// If every type inside a tuple implements one of the following
368 /// traits, then a tuple itself also implements it.
369 ///
370 /// * `Clone`
371 /// * `PartialEq`
372 /// * `Eq`
373 /// * `PartialOrd`
374 /// * `Ord`
375 /// * `Debug`
376 /// * `Default`
377 /// * `Hash`
378 ///
379 /// # Examples
380 ///
381 /// Accessing elements of a tuple at specified indices:
382 ///
383 /// ```
384 /// let x = ("colorless",  "green", "ideas", "sleep", "furiously");
385 /// assert_eq!(x.3, "sleep");
386 ///
387 /// let v = (3, 3);
388 /// let u = (1, -5);
389 /// assert_eq!(v.0 * u.0 + v.1 * u.1, -12);
390 /// ```
391 ///
392 /// Using traits implemented for tuples:
393 ///
394 /// ```
395 /// let a = (1, 2);
396 /// let b = (3, 4);
397 /// assert!(a != b);
398 ///
399 /// let c = b.clone();
400 /// assert!(b == c);
401 ///
402 /// let d : (u32, f32) = Default::default();
403 /// assert_eq!(d, (0, 0.0f32));
404 /// ```
405 ///
406 mod prim_tuple { }
407
408 #[doc(primitive = "f32")]
409 /// The 32-bit floating point type.
410 ///
411 /// *[See also the `std::f32` module](f32/index.html).*
412 ///
413 mod prim_f32 { }
414
415 #[doc(primitive = "f64")]
416 //
417 /// The 64-bit floating point type.
418 ///
419 /// *[See also the `std::f64` module](f64/index.html).*
420 ///
421 mod prim_f64 { }
422
423 #[doc(primitive = "i8")]
424 //
425 /// The 8-bit signed integer type.
426 ///
427 /// *[See also the `std::i8` module](i8/index.html).*
428 ///
429 mod prim_i8 { }
430
431 #[doc(primitive = "i16")]
432 //
433 /// The 16-bit signed integer type.
434 ///
435 /// *[See also the `std::i16` module](i16/index.html).*
436 ///
437 mod prim_i16 { }
438
439 #[doc(primitive = "i32")]
440 //
441 /// The 32-bit signed integer type.
442 ///
443 /// *[See also the `std::i32` module](i32/index.html).*
444 ///
445 mod prim_i32 { }
446
447 #[doc(primitive = "i64")]
448 //
449 /// The 64-bit signed integer type.
450 ///
451 /// *[See also the `std::i64` module](i64/index.html).*
452 ///
453 mod prim_i64 { }
454
455 #[doc(primitive = "u8")]
456 //
457 /// The 8-bit unsigned integer type.
458 ///
459 /// *[See also the `std::u8` module](u8/index.html).*
460 ///
461 mod prim_u8 { }
462
463 #[doc(primitive = "u16")]
464 //
465 /// The 16-bit unsigned integer type.
466 ///
467 /// *[See also the `std::u16` module](u16/index.html).*
468 ///
469 mod prim_u16 { }
470
471 #[doc(primitive = "u32")]
472 //
473 /// The 32-bit unsigned integer type.
474 ///
475 /// *[See also the `std::u32` module](u32/index.html).*
476 ///
477 mod prim_u32 { }
478
479 #[doc(primitive = "u64")]
480 //
481 /// The 64-bit unsigned integer type.
482 ///
483 /// *[See also the `std::u64` module](u64/index.html).*
484 ///
485 mod prim_u64 { }
486
487 #[doc(primitive = "isize")]
488 //
489 /// The pointer-sized signed integer type.
490 ///
491 /// *[See also the `std::isize` module](isize/index.html).*
492 ///
493 mod prim_isize { }
494
495 #[doc(primitive = "usize")]
496 //
497 /// The pointer-sized unsigned integer type.
498 ///
499 /// *[See also the `std::usize` module](usize/index.html).*
500 ///
501 mod prim_usize { }
502