]> git.lizzy.rs Git - rust.git/blob - src/libstd/keyword_docs.rs
3eec5468c7de44648d375fe8ba00cdc1ef4c6fbd
[rust.git] / src / libstd / keyword_docs.rs
1 #[doc(keyword = "as")]
2 //
3 /// The keyword for casting a value to a type.
4 ///
5 /// `as` is most commonly used to turn primitive types into other primitive types, but it has other
6 /// uses that include turning pointers into addresses, addresses into pointers, and pointers into
7 /// other pointers.
8 ///
9 /// ```rust
10 /// let thing1: u8 = 89.0 as u8;
11 /// assert_eq!('B' as u32, 66);
12 /// assert_eq!(thing1 as char, 'Y');
13 /// let thing2: f32 = thing1 as f32 + 10.5;
14 /// assert_eq!(true as u8 + thing2 as u8, 100);
15 /// ```
16 ///
17 /// In general, any cast that can be performed via ascribing the type can also be done using `as`,
18 /// so instead of writing `let x: u32 = 123`, you can write `let x = 123 as u32` (Note: `let x: u32
19 /// = 123` would be best in that situation). The same is not true in the other direction, however,
20 /// explicitly using `as` allows a few more coercions that aren't allowed implicitly, such as
21 /// changing the type of a raw pointer or turning closures into raw pointers.
22 ///
23 /// Other places `as` is used include as extra syntax for [`crate`] and `use`, to change the name
24 /// something is imported as.
25 ///
26 /// For more information on what `as` is capable of, see the [Reference]
27 ///
28 /// [Reference]:
29 /// https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions
30 /// [`crate`]: keyword.crate.html
31 mod as_keyword { }
32
33 #[doc(keyword = "const")]
34 //
35 /// The keyword for defining constants.
36 ///
37 /// Sometimes a certain value is used many times throughout a program, and it can become
38 /// inconvenient to copy it over and over. What's more, it's not always possible or desirable to
39 /// make it a variable that gets carried around to each function that needs it. In these cases, the
40 /// `const` keyword provides a convenient alternative to code duplication.
41 ///
42 /// ```rust
43 /// const THING: u32 = 0xABAD1DEA;
44 ///
45 /// let foo = 123 + THING;
46 /// ```
47 ///
48 /// Constants must be explicitly typed, unlike with `let` you can't ignore its type and let the
49 /// compiler figure it out. Any constant value can be defined in a const, which in practice happens
50 /// to be most things that would be reasonable to have a constant (barring `const fn`s). For
51 /// example, you can't have a File as a `const`.
52 ///
53 /// The only lifetime allowed in a constant is `'static`, which is the lifetime that encompasses
54 /// all others in a Rust program. For example, if you wanted to define a constant string, it would
55 /// look like this:
56 ///
57 /// ```rust
58 /// const WORDS: &str = "hello rust!";
59 /// ```
60 ///
61 /// Thanks to static lifetime elision, you usually don't have to explicitly use 'static:
62 ///
63 /// ```rust
64 /// const WORDS: &str = "hello convenience!";
65 /// ```
66 ///
67 /// `const` items looks remarkably similar to `static` items, which introduces some confusion as
68 /// to which one should be used at which times. To put it simply, constants are inlined wherever
69 /// they're used, making using them identical to simply replacing the name of the const with its
70 /// value. Static variables on the other hand point to a single location in memory, which all
71 /// accesses share. This means that, unlike with constants, they can't have destructors, and act as
72 /// a single value across the entire codebase.
73 ///
74 /// Constants, as with statics, should always be in SCREAMING_SNAKE_CASE.
75 ///
76 /// The `const` keyword is also used in raw pointers in combination with `mut`, as seen in `*const
77 /// T` and `*mut T`. More about that can be read at the [pointer] primitive part of the Rust docs.
78 ///
79 /// For more detail on `const`, see the [Rust Book] or the [Reference]
80 ///
81 /// [pointer]: primitive.pointer.html
82 /// [Rust Book]:
83 /// https://doc.rust-lang.org/stable/book/2018-edition/ch03-01-variables-and-mutability.html#differences-between-variables-and-constants
84 /// [Reference]: https://doc.rust-lang.org/reference/items/constant-items.html
85 mod const_keyword { }
86
87 #[doc(keyword = "crate")]
88 //
89 /// The `crate` keyword.
90 ///
91 /// The primary use of the `crate` keyword is as a part of `extern crate` declarations, which are
92 /// used to specify a dependency on a crate external to the one it's declared in. Crates are the
93 /// fundamental compilation unit of Rust code, and can be seen as libraries or projects. More can
94 /// be read about crates in the [Reference].
95 ///
96 /// ```rust ignore
97 /// extern crate rand;
98 /// extern crate my_crate as thing;
99 /// extern crate std; // implicitly added to the root of every Rust project
100 /// ```
101 ///
102 /// The `as` keyword can be used to change what the crate is referred to as in your project. If a
103 /// crate name includes a dash, it is implicitly imported with the dashes replaced by underscores.
104 ///
105 /// `crate` is also used as in conjunction with `pub` to signify that the item it's attached to
106 /// is public only to other members of the same crate it's in.
107 ///
108 /// ```rust
109 /// # #[allow(unused_imports)]
110 /// pub(crate) use std::io::Error as IoError;
111 /// pub(crate) enum CoolMarkerType { }
112 /// pub struct PublicThing {
113 ///     pub(crate) semi_secret_thing: bool,
114 /// }
115 /// ```
116 ///
117 /// [Reference]: https://doc.rust-lang.org/reference/items/extern-crates.html
118 mod crate_keyword { }
119
120 #[doc(keyword = "enum")]
121 //
122 /// For defining enumerations.
123 ///
124 /// Enums in Rust are similar to those of other compiled languages like C, but have important
125 /// differences that make them considerably more powerful. What Rust calls enums are more commonly
126 /// known as [Algebraic Data Types] if you're coming from a functional programming background. The
127 /// important detail is that each enum variant can have data to go along with it.
128 ///
129 /// ```rust
130 /// # struct Coord;
131 /// enum SimpleEnum {
132 ///     FirstVariant,
133 ///     SecondVariant,
134 ///     ThirdVariant,
135 /// }
136 ///
137 /// enum Location {
138 ///     Unknown,
139 ///     Anonymous,
140 ///     Known(Coord),
141 /// }
142 ///
143 /// enum ComplexEnum {
144 ///     Nothing,
145 ///     Something(u32),
146 ///     LotsOfThings {
147 ///         usual_struct_stuff: bool,
148 ///         blah: String,
149 ///     }
150 /// }
151 ///
152 /// enum EmptyEnum { }
153 /// ```
154 ///
155 /// The first enum shown is the usual kind of enum you'd find in a C-style language. The second
156 /// shows off a hypothetical example of something storing location data, with `Coord` being any
157 /// other type that's needed, for example a struct. The third example demonstrates the kind of
158 /// data a variant can store, ranging from nothing, to a tuple, to an anonymous struct.
159 ///
160 /// Instantiating enum variants involves explicitly using the enum's name as its namespace,
161 /// followed by one of its variants. `SimpleEnum::SecondVariant` would be an example from above.
162 /// When data follows along with a variant, such as with rust's built-in [`Option`] type, the data
163 /// is added as the type describes, for example `Option::Some(123)`. The same follows with
164 /// struct-like variants, with things looking like `ComplexEnum::LotsOfThings { usual_struct_stuff:
165 /// true, blah: "hello!".to_string(), }`. Empty Enums are similar to () in that they cannot be
166 /// instantiated at all, and are used mainly to mess with the type system in interesting ways.
167 ///
168 /// For more information, take a look at the [Rust Book] or the [Reference]
169 ///
170 /// [Algebraic Data Types]: https://en.wikipedia.org/wiki/Algebraic_data_type
171 /// [`Option`]: option/enum.Option.html
172 /// [Rust Book]: https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html
173 /// [Reference]: https://doc.rust-lang.org/reference/items/enumerations.html
174 mod enum_keyword { }
175
176 #[doc(keyword = "extern")]
177 //
178 /// For external connections in Rust code.
179 ///
180 /// The `extern` keyword is used in two places in Rust. One is in conjunction with the [`crate`]
181 /// keyword to make your Rust code aware of other Rust crates in your project, i.e., `extern crate
182 /// lazy_static;`. The other use is in foreign function interfaces (FFI).
183 ///
184 /// `extern` is used in two different contexts within FFI. The first is in the form of external
185 /// blocks, for declaring function interfaces that Rust code can call foreign code by.
186 ///
187 /// ```rust ignore
188 /// #[link(name = "my_c_library")]
189 /// extern "C" {
190 ///     fn my_c_function(x: i32) -> bool;
191 /// }
192 /// ```
193 ///
194 /// This code would attempt to link with `libmy_c_library.so` on unix-like systems and
195 /// `my_c_library.dll` on Windows at runtime, and panic if it can't find something to link to. Rust
196 /// code could then use `my_c_function` as if it were any other unsafe Rust function. Working with
197 /// non-Rust languages and FFI is inherently unsafe, so wrappers are usually built around C APIs.
198 ///
199 /// The mirror use case of FFI is also done via the `extern` keyword:
200 ///
201 /// ```rust
202 /// #[no_mangle]
203 /// pub extern fn callable_from_c(x: i32) -> bool {
204 ///     x % 3 == 0
205 /// }
206 /// ```
207 ///
208 /// If compiled as a dylib, the resulting .so could then be linked to from a C library, and the
209 /// function could be used as if it was from any other library.
210 ///
211 /// For more information on FFI, check the [Rust book] or the [Reference].
212 ///
213 /// [Rust book]:
214 /// https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html#using-extern-functions-to-call-external-code
215 /// [Reference]: https://doc.rust-lang.org/reference/items/external-blocks.html
216 mod extern_keyword { }
217
218 #[doc(keyword = "fn")]
219 //
220 /// The keyword for defining functions.
221 ///
222 /// Functions are the primary way code is executed within Rust. Function blocks, usually just
223 /// called functions, can be defined in a variety of different places and be assigned many
224 /// different attributes and modifiers.
225 ///
226 /// Standalone functions that just sit within a module not attached to anything else are common,
227 /// but most functions will end up being inside [`impl`] blocks, either on another type itself, or
228 /// as a trait impl for that type.
229 ///
230 /// ```rust
231 /// fn standalone_function() {
232 ///     // code
233 /// }
234 ///
235 /// pub fn public_thing(argument: bool) -> String {
236 ///     // code
237 ///     # "".to_string()
238 /// }
239 ///
240 /// struct Thing {
241 ///     foo: i32,
242 /// }
243 ///
244 /// impl Thing {
245 ///     pub fn new() -> Self {
246 ///         Self {
247 ///             foo: 42,
248 ///         }
249 ///     }
250 /// }
251 /// ```
252 ///
253 /// In addition to presenting fixed types in the form of `fn name(arg: type, ..) -> return_type`,
254 /// functions can also declare a list of type parameters along with trait bounds that they fall
255 /// into.
256 ///
257 /// ```rust
258 /// fn generic_function<T: Clone>(x: T) -> (T, T, T) {
259 ///     (x.clone(), x.clone(), x.clone())
260 /// }
261 ///
262 /// fn generic_where<T>(x: T) -> T
263 ///     where T: std::ops::Add<Output = T> + Copy
264 /// {
265 ///     x + x + x
266 /// }
267 /// ```
268 ///
269 /// Declaring trait bounds in the angle brackets is functionally identical to using a `where`
270 /// clause. It's up to the programmer to decide which works better in each situation, but `where`
271 /// tends to be better when things get longer than one line.
272 ///
273 /// Along with being made public via `pub`, `fn` can also have an [`extern`] added for use in
274 /// FFI.
275 ///
276 /// For more information on the various types of functions and how they're used, consult the [Rust
277 /// book] or the [Reference].
278 ///
279 /// [`impl`]: keyword.impl.html
280 /// [`extern`]: keyword.extern.html
281 /// [Rust book]: https://doc.rust-lang.org/book/ch03-03-how-functions-work.html
282 /// [Reference]: https://doc.rust-lang.org/reference/items/functions.html
283 mod fn_keyword { }
284
285 #[doc(keyword = "for")]
286 //
287 /// The `for` keyword.
288 ///
289 /// The `for` keyword is used in many syntactic locations:
290 ///
291 /// * `for` is used in for-in-loops (see below).
292 /// * `for` is used when implementing traits as in `impl Trait for Type` (see [`impl`] for more info
293 ///   on that).
294 /// * `for` is also used for [higher-ranked trait bounds] as in `for<'a> &'a T: PartialEq<i32>`.
295 ///
296 /// for-in-loops, or to be more precise, iterator loops, are a simple syntactic sugar over a common
297 /// practice within Rust, which is to loop over an iterator until that iterator returns `None` (or
298 /// `break` is called).
299 ///
300 /// ```rust
301 /// for i in 0..5 {
302 ///     println!("{}", i * 2);
303 /// }
304 ///
305 /// for i in std::iter::repeat(5) {
306 ///     println!("turns out {} never stops being 5", i);
307 ///     break; // would loop forever otherwise
308 /// }
309 ///
310 /// 'outer: for x in 5..50 {
311 ///     for y in 0..10 {
312 ///         if x == y {
313 ///             break 'outer;
314 ///         }
315 ///     }
316 /// }
317 /// ```
318 ///
319 /// As shown in the example above, `for` loops (along with all other loops) can be tagged, using
320 /// similar syntax to lifetimes (only visually similar, entirely distinct in practice). Giving the
321 /// same tag to `break` breaks the tagged loop, which is useful for inner loops. It is definitely
322 /// not a goto.
323 ///
324 /// A `for` loop expands as shown:
325 ///
326 /// ```rust
327 /// # fn code() { }
328 /// # let iterator = 0..2;
329 /// for loop_variable in iterator {
330 ///     code()
331 /// }
332 /// ```
333 ///
334 /// ```rust
335 /// # fn code() { }
336 /// # let iterator = 0..2;
337 /// {
338 ///     let mut _iter = std::iter::IntoIterator::into_iter(iterator);
339 ///     loop {
340 ///         match _iter.next() {
341 ///             Some(loop_variable) => {
342 ///                 code()
343 ///             },
344 ///             None => break,
345 ///         }
346 ///     }
347 /// }
348 /// ```
349 ///
350 /// More details on the functionality shown can be seen at the [`IntoIterator`] docs.
351 ///
352 /// For more information on for-loops, see the [Rust book] or the [Reference].
353 ///
354 /// [`impl`]: keyword.impl.html
355 /// [`IntoIterator`]: iter/trait.IntoIterator.html
356 /// [Rust book]:
357 /// https://doc.rust-lang.org/book/2018-edition/ch03-05-control-flow.html#looping-through-a-collection-with-for
358 /// [Reference]: https://doc.rust-lang.org/reference/expressions/loop-expr.html#iterator-loops
359 mod for_keyword { }
360
361 #[doc(keyword = "if")]
362 //
363 /// If statements and expressions.
364 ///
365 /// `if` is a familiar construct to most programmers, and is the main way you'll often do logic in
366 /// your code. However, unlike in most languages, `if` blocks can also act as expressions.
367 ///
368 /// ```rust
369 /// # let rude = true;
370 /// if 1 == 2 {
371 ///     println!("whoops, mathematics broke");
372 /// } else {
373 ///     println!("everything's fine!");
374 /// }
375 ///
376 /// let greeting = if rude {
377 ///     "sup nerd."
378 /// } else {
379 ///     "hello, friend!"
380 /// };
381 ///
382 /// if let Ok(x) = "123".parse::<i32>() {
383 ///     println!("{} double that and you get {}!", greeting, x * 2);
384 /// }
385 /// ```
386 ///
387 /// Shown above are the three typical forms an `if` block comes in. First is the usual kind of
388 /// thing you'd see in many languages, with an optional `else` block. Second uses `if` as an
389 /// expression, which is only possible if all branches return the same type. An `if` expression can
390 /// be used everywhere you'd expect. The third kind of `if` block is an `if let` block, which
391 /// behaves similarly to using a `match` expression:
392 ///
393 /// ```rust
394 /// if let Some(x) = Some(123) {
395 ///     // code
396 ///     # let _ = x;
397 /// } else {
398 ///     // something else
399 /// }
400 ///
401 /// match Some(123) {
402 ///     Some(x) => {
403 ///         // code
404 ///         # let _ = x;
405 ///     },
406 ///     _ => {
407 ///         // something else
408 ///     },
409 /// }
410 /// ```
411 ///
412 /// Each kind of `if` expression can be mixed and matched as needed.
413 ///
414 /// ```rust
415 /// if true == false {
416 ///     println!("oh no");
417 /// } else if "something" == "other thing" {
418 ///     println!("oh dear");
419 /// } else if let Some(200) = "blarg".parse::<i32>().ok() {
420 ///     println!("uh oh");
421 /// } else {
422 ///     println!("phew, nothing's broken");
423 /// }
424 /// ```
425 ///
426 /// The `if` keyword is used in one other place in Rust, namely as a part of pattern matching
427 /// itself, allowing patterns such as `Some(x) if x > 200` to be used.
428 ///
429 /// For more information on `if` expressions, see the [Rust book] or the [Reference].
430 ///
431 /// [Rust book]:
432 /// https://doc.rust-lang.org/stable/book/2018-edition/ch03-05-control-flow.html#if-expressions
433 /// [Reference]: https://doc.rust-lang.org/reference/expressions/if-expr.html
434 mod if_keyword { }
435
436 #[doc(keyword = "impl")]
437 //
438 /// The implementation-defining keyword.
439 ///
440 /// The `impl` keyword is primarily used to define implementations on types. Inherent
441 /// implementations are standalone, while trait implementations are used to implement traits for
442 /// types, or other traits.
443 ///
444 /// Functions and consts can both be defined in an implementation. A function defined in an
445 /// `impl` block can be standalone, meaning it would be called like `Foo::bar()`. If the function
446 /// takes `self`, `&self`, or `&mut self` as its first argument, it can also be called using
447 /// method-call syntax, a familiar feature to any object oriented programmer, like `foo.bar()`.
448 ///
449 /// ```rust
450 /// struct Example {
451 ///     number: i32,
452 /// }
453 ///
454 /// impl Example {
455 ///     fn boo() {
456 ///         println!("boo! Example::boo() was called!");
457 ///     }
458 ///
459 ///     fn answer(&mut self) {
460 ///         self.number += 42;
461 ///     }
462 ///
463 ///     fn get_number(&self) -> i32 {
464 ///         self.number
465 ///     }
466 /// }
467 ///
468 /// trait Thingy {
469 ///     fn do_thingy(&self);
470 /// }
471 ///
472 /// impl Thingy for Example {
473 ///     fn do_thingy(&self) {
474 ///         println!("doing a thing! also, number is {}!", self.number);
475 ///     }
476 /// }
477 /// ```
478 ///
479 /// For more information on implementations, see the [Rust book][book1] or the [Reference].
480 ///
481 /// The other use of the `impl` keyword is in `impl Trait` syntax, which can be seen as a shorthand
482 /// for "a concrete type that implements this trait". Its primary use is working with closures,
483 /// which have type definitions generated at compile time that can't be simply typed out.
484 ///
485 /// ```rust
486 /// fn thing_returning_closure() -> impl Fn(i32) -> bool {
487 ///     println!("here's a closure for you!");
488 ///     |x: i32| x % 3 == 0
489 /// }
490 /// ```
491 ///
492 /// For more information on `impl Trait` syntax, see the [Rust book][book2].
493 ///
494 /// [book1]: https://doc.rust-lang.org/stable/book/2018-edition/ch05-03-method-syntax.html
495 /// [Reference]: https://doc.rust-lang.org/reference/items/implementations.html
496 /// [book2]:
497 /// https://doc.rust-lang.org/stable/book/2018-edition/ch10-02-traits.html#returning-traits
498 mod impl_keyword { }
499
500 #[doc(keyword = "let")]
501 //
502 /// The variable binding keyword.
503 ///
504 /// The primary use for the `let` keyword is in `let` statements, which are used to introduce a new
505 /// set of variables into the current scope, as given by a pattern.
506 ///
507 /// ```rust
508 /// # #![allow(unused_assignments)]
509 /// let thing1: i32 = 100;
510 /// let thing2 = 200 + thing1;
511 ///
512 /// let mut changing_thing = true;
513 /// changing_thing = false;
514 ///
515 /// let (part1, part2) = ("first", "second");
516 ///
517 /// struct Example {
518 ///     a: bool,
519 ///     b: u64,
520 /// }
521 ///
522 /// let Example { a, b: _ } = Example {
523 ///     a: true,
524 ///     b: 10004,
525 /// };
526 /// assert!(a);
527 /// ```
528 ///
529 /// The pattern is most commonly a single variable, which means no pattern matching is done and
530 /// the expression given is bound to the variable. Apart from that, patterns used in `let` bindings
531 /// can be as complicated as needed, given that the pattern is exhaustive. See the [Rust
532 /// book][book1] for more information on pattern matching. The type of the pattern is optionally
533 /// given afterwards, but if left blank is automatically inferred by the compiler if possible.
534 ///
535 /// Variables in Rust are immutable by default, and require the `mut` keyword to be made mutable.
536 ///
537 /// Multiple variables can be defined with the same name, known as shadowing. This doesn't affect
538 /// the original variable in any way beyond being unable to directly access it beyond the point of
539 /// shadowing. It continues to remain in scope, getting dropped only when it falls out of scope.
540 /// Shadowed variables don't need to have the same type as the variables shadowing them.
541 ///
542 /// ```rust
543 /// let shadowing_example = true;
544 /// let shadowing_example = 123.4;
545 /// let shadowing_example = shadowing_example as u32;
546 /// let mut shadowing_example = format!("cool! {}", shadowing_example);
547 /// shadowing_example += " something else!"; // not shadowing
548 /// ```
549 ///
550 /// Other places the `let` keyword is used include along with [`if`], in the form of `if let`
551 /// expressions. They're useful if the pattern being matched isn't exhaustive, such as with
552 /// enumerations. `while let` also exists, which runs a loop with a pattern matched value until
553 /// that pattern can't be matched.
554 ///
555 /// For more information on the `let` keyword, see the [Rust book] or the [Reference]
556 ///
557 /// [book1]: https://doc.rust-lang.org/stable/book/2018-edition/ch06-02-match.html
558 /// [`if`]: keyword.if.html
559 /// [book2]:
560 /// https://doc.rust-lang.org/stable/book/2018-edition/ch18-01-all-the-places-for-patterns.html#let-statements
561 /// [Reference]: https://doc.rust-lang.org/reference/statements.html#let-statements
562 mod let_keyword { }
563
564 #[doc(keyword = "loop")]
565 //
566 /// The loop-defining keyword.
567 ///
568 /// `loop` is used to define the simplest kind of loop supported in Rust. It runs the code inside
569 /// it until the code uses `break` or the program exits.
570 ///
571 /// ```rust
572 /// loop {
573 ///     println!("hello world forever!");
574 ///     # break;
575 /// }
576 ///
577 /// let mut i = 0;
578 /// loop {
579 ///     println!("i is {}", i);
580 ///     if i > 10 {
581 ///         break;
582 ///     }
583 ///     i += 1;
584 /// }
585 /// ```
586 ///
587 /// Unlike the other kinds of loops in Rust (`while`, `while let`, and `for`), loops can be used as
588 /// expressions that return values via `break`.
589 ///
590 /// ```rust
591 /// let mut i = 1;
592 /// let something = loop {
593 ///     i *= 2;
594 ///     if i > 100 {
595 ///         break i;
596 ///     }
597 /// };
598 /// assert_eq!(something, 128);
599 /// ```
600 ///
601 /// Every `break` in a loop has to have the same type. When it's not explicitly giving something,
602 /// `break;` returns `()`.
603 ///
604 /// For more information on `loop` and loops in general, see the [Reference].
605 ///
606 /// [Reference]: https://doc.rust-lang.org/reference/expressions/loop-expr.html
607 mod loop_keyword { }
608
609 #[doc(keyword = "struct")]
610 //
611 /// The keyword used to define structs.
612 ///
613 /// Structs in Rust come in three flavors: Structs with named fields, tuple structs, and unit
614 /// structs.
615 ///
616 /// ```rust
617 /// struct Regular {
618 ///     field1: f32,
619 ///     field2: String,
620 ///     pub field3: bool
621 /// }
622 ///
623 /// struct Tuple(u32, String);
624 ///
625 /// struct Unit;
626 /// ```
627 ///
628 /// Regular structs are the most commonly used. Each field defined within them has a name and a
629 /// type, and once defined can be accessed using `example_struct.field` syntax. The fields of a
630 /// struct share its mutability, so `foo.bar = 2;` would only be valid if `foo` was mutable. Adding
631 /// `pub` to a field makes it visible to code in other modules, as well as allowing it to be
632 /// directly accessed and modified.
633 ///
634 /// Tuple structs are similar to regular structs, but its fields have no names. They are used like
635 /// tuples, with deconstruction possible via `let TupleStruct(x, y) = foo;` syntax. For accessing
636 /// individual variables, the same syntax is used as with regular tuples, namely `foo.0`, `foo.1`,
637 /// etc, starting at zero.
638 ///
639 /// Unit structs are most commonly used as marker. They have a size of zero bytes, but unlike empty
640 /// enums they can be instantiated, making them isomorphic to the unit type `()`. Unit structs are
641 /// useful when you need to implement a trait on something, but don't need to store any data inside
642 /// it.
643 ///
644 /// # Instantiation
645 ///
646 /// Structs can be instantiated in different ways, all of which can be mixed and
647 /// matched as needed. The most common way to make a new struct is via a constructor method such as
648 /// `new()`, but when that isn't available (or you're writing the constructor itself), struct
649 /// literal syntax is used:
650 ///
651 /// ```rust
652 /// # struct Foo { field1: f32, field2: String, etc: bool }
653 /// let example = Foo {
654 ///     field1: 42.0,
655 ///     field2: "blah".to_string(),
656 ///     etc: true,
657 /// };
658 /// ```
659 ///
660 /// It's only possible to directly instantiate a struct using struct literal syntax when all of its
661 /// fields are visible to you.
662 ///
663 /// There are a handful of shortcuts provided to make writing constructors more convenient, most
664 /// common of which is the Field Init shorthand. When there is a variable and a field of the same
665 /// name, the assignment can be simplified from `field: field` into simply `field`. The following
666 /// example of a hypothetical constructor demonstrates this:
667 ///
668 /// ```rust
669 /// struct User {
670 ///     name: String,
671 ///     admin: bool,
672 /// }
673 ///
674 /// impl User {
675 ///     pub fn new(name: String) -> Self {
676 ///         Self {
677 ///             name,
678 ///             admin: false,
679 ///         }
680 ///     }
681 /// }
682 /// ```
683 ///
684 /// Another shortcut for struct instantiation is available, used when you need to make a new
685 /// struct that has the same values as most of a previous struct of the same type, called struct
686 /// update syntax:
687 ///
688 /// ```rust
689 /// # struct Foo { field1: String, field2: () }
690 /// # let thing = Foo { field1: "".to_string(), field2: () };
691 /// let updated_thing = Foo {
692 ///     field1: "a new value".to_string(),
693 ///     ..thing
694 /// };
695 /// ```
696 ///
697 /// Tuple structs are instantiated in the same way as tuples themselves, except with the struct's
698 /// name as a prefix: `Foo(123, false, 0.1)`.
699 ///
700 /// Empty structs are instantiated with just their name, and don't need anything else. `let thing =
701 /// EmptyStruct;`
702 ///
703 /// # Style conventions
704 ///
705 /// Structs are always written in CamelCase, with few exceptions. While the trailing comma on a
706 /// struct's list of fields can be omitted, it's usually kept for convenience in adding and
707 /// removing fields down the line.
708 ///
709 /// For more information on structs, take a look at the [Rust Book][book] or the
710 /// [Reference][reference].
711 ///
712 /// [`PhantomData`]: marker/struct.PhantomData.html
713 /// [book]: https://doc.rust-lang.org/book/ch05-01-defining-structs.html
714 /// [reference]: https://doc.rust-lang.org/reference/items/structs.html
715 mod struct_keyword { }