]> git.lizzy.rs Git - rust.git/blob - src/doc/reference/src/items.md
clean up some things
[rust.git] / src / doc / reference / src / items.md
1 # Items
2
3 An _item_ is a component of a crate. Items are organized within a crate by a
4 nested set of [modules](#modules). Every crate has a single "outermost"
5 anonymous module; all further items within the crate have [paths](#paths)
6 within the module tree of the crate.
7
8 Items are entirely determined at compile-time, generally remain fixed during
9 execution, and may reside in read-only memory.
10
11 There are several kinds of item:
12
13 * [`extern crate` declarations](#extern-crate-declarations)
14 * [`use` declarations](#use-declarations)
15 * [modules](#modules)
16 * [function definitions](#functions)
17 * [`extern` blocks](#external-blocks)
18 * [type definitions](grammar.html#type-definitions)
19 * [struct definitions](#structs)
20 * [enumeration definitions](#enumerations)
21 * [constant items](#constant-items)
22 * [static items](#static-items)
23 * [trait definitions](#traits)
24 * [implementations](#implementations)
25
26 Some items form an implicit scope for the declaration of sub-items. In other
27 words, within a function or module, declarations of items can (in many cases)
28 be mixed with the statements, control blocks, and similar artifacts that
29 otherwise compose the item body. The meaning of these scoped items is the same
30 as if the item was declared outside the scope — it is still a static item
31 — except that the item's *path name* within the module namespace is
32 qualified by the name of the enclosing item, or is private to the enclosing
33 item (in the case of functions). The grammar specifies the exact locations in
34 which sub-item declarations may appear.
35
36 ## Type Parameters
37
38 All items except modules, constants and statics may be *parameterized* by type.
39 Type parameters are given as a comma-separated list of identifiers enclosed in
40 angle brackets (`<...>`), after the name of the item and before its definition.
41 The type parameters of an item are considered "part of the name", not part of
42 the type of the item. A referencing [path](#paths) must (in principle) provide
43 type arguments as a list of comma-separated types enclosed within angle
44 brackets, in order to refer to the type-parameterized item. In practice, the
45 type-inference system can usually infer such argument types from context. There
46 are no general type-parametric types, only type-parametric items. That is, Rust
47 has no notion of type abstraction: there are no higher-ranked (or "forall") types
48 abstracted over other types, though higher-ranked types do exist for lifetimes.
49
50 ## Modules
51
52 A module is a container for zero or more [items](#items).
53
54 A _module item_ is a module, surrounded in braces, named, and prefixed with the
55 keyword `mod`. A module item introduces a new, named module into the tree of
56 modules making up a crate. Modules can nest arbitrarily.
57
58 An example of a module:
59
60 ```
61 mod math {
62     type Complex = (f64, f64);
63     fn sin(f: f64) -> f64 {
64         /* ... */
65 # panic!();
66     }
67     fn cos(f: f64) -> f64 {
68         /* ... */
69 # panic!();
70     }
71     fn tan(f: f64) -> f64 {
72         /* ... */
73 # panic!();
74     }
75 }
76 ```
77
78 Modules and types share the same namespace. Declaring a named type with
79 the same name as a module in scope is forbidden: that is, a type definition,
80 trait, struct, enumeration, or type parameter can't shadow the name of a module
81 in scope, or vice versa.
82
83 A module without a body is loaded from an external file, by default with the
84 same name as the module, plus the `.rs` extension. When a nested submodule is
85 loaded from an external file, it is loaded from a subdirectory path that
86 mirrors the module hierarchy.
87
88 ```{.ignore}
89 // Load the `vec` module from `vec.rs`
90 mod vec;
91
92 mod thread {
93     // Load the `local_data` module from `thread/local_data.rs`
94     // or `thread/local_data/mod.rs`.
95     mod local_data;
96 }
97 ```
98
99 The directories and files used for loading external file modules can be
100 influenced with the `path` attribute.
101
102 ```{.ignore}
103 #[path = "thread_files"]
104 mod thread {
105     // Load the `local_data` module from `thread_files/tls.rs`
106     #[path = "tls.rs"]
107     mod local_data;
108 }
109 ```
110
111 ### Extern crate declarations
112
113 An _`extern crate` declaration_ specifies a dependency on an external crate.
114 The external crate is then bound into the declaring scope as the `ident`
115 provided in the `extern_crate_decl`.
116
117 The external crate is resolved to a specific `soname` at compile time, and a
118 runtime linkage requirement to that `soname` is passed to the linker for
119 loading at runtime. The `soname` is resolved at compile time by scanning the
120 compiler's library path and matching the optional `crateid` provided against
121 the `crateid` attributes that were declared on the external crate when it was
122 compiled. If no `crateid` is provided, a default `name` attribute is assumed,
123 equal to the `ident` given in the `extern_crate_decl`.
124
125 Three examples of `extern crate` declarations:
126
127 ```{.ignore}
128 extern crate pcre;
129
130 extern crate std; // equivalent to: extern crate std as std;
131
132 extern crate std as ruststd; // linking to 'std' under another name
133 ```
134
135 When naming Rust crates, hyphens are disallowed. However, Cargo packages may
136 make use of them. In such case, when `Cargo.toml` doesn't specify a crate name,
137 Cargo will transparently replace `-` with `_` (Refer to [RFC 940] for more
138 details).
139
140 Here is an example:
141
142 ```{.ignore}
143 // Importing the Cargo package hello-world
144 extern crate hello_world; // hyphen replaced with an underscore
145 ```
146
147 [RFC 940]: https://github.com/rust-lang/rfcs/blob/master/text/0940-hyphens-considered-harmful.md
148
149 ### Use declarations
150
151 A _use declaration_ creates one or more local name bindings synonymous with
152 some other [path](#paths). Usually a `use` declaration is used to shorten the
153 path required to refer to a module item. These declarations may appear in
154 [modules](#modules) and [blocks](grammar.html#block-expressions), usually at the top.
155
156 > **Note**: Unlike in many languages,
157 > `use` declarations in Rust do *not* declare linkage dependency with external crates.
158 > Rather, [`extern crate` declarations](#extern-crate-declarations) declare linkage dependencies.
159
160 Use declarations support a number of convenient shortcuts:
161
162 * Rebinding the target name as a new local name, using the syntax `use p::q::r as x;`
163 * Simultaneously binding a list of paths differing only in their final element,
164   using the glob-like brace syntax `use a::b::{c,d,e,f};`
165 * Binding all paths matching a given prefix, using the asterisk wildcard syntax
166   `use a::b::*;`
167 * Simultaneously binding a list of paths differing only in their final element
168   and their immediate parent module, using the `self` keyword, such as
169   `use a::b::{self, c, d};`
170
171 An example of `use` declarations:
172
173 ```rust
174 use std::option::Option::{Some, None};
175 use std::collections::hash_map::{self, HashMap};
176
177 fn foo<T>(_: T){}
178 fn bar(map1: HashMap<String, usize>, map2: hash_map::HashMap<String, usize>){}
179
180 fn main() {
181     // Equivalent to 'foo(vec![std::option::Option::Some(1.0f64),
182     // std::option::Option::None]);'
183     foo(vec![Some(1.0f64), None]);
184
185     // Both `hash_map` and `HashMap` are in scope.
186     let map1 = HashMap::new();
187     let map2 = hash_map::HashMap::new();
188     bar(map1, map2);
189 }
190 ```
191
192 Like items, `use` declarations are private to the containing module, by
193 default. Also like items, a `use` declaration can be public, if qualified by
194 the `pub` keyword. Such a `use` declaration serves to _re-export_ a name. A
195 public `use` declaration can therefore _redirect_ some public name to a
196 different target definition: even a definition with a private canonical path,
197 inside a different module. If a sequence of such redirections form a cycle or
198 cannot be resolved unambiguously, they represent a compile-time error.
199
200 An example of re-exporting:
201
202 ```
203 # fn main() { }
204 mod quux {
205     pub use quux::foo::{bar, baz};
206
207     pub mod foo {
208         pub fn bar() { }
209         pub fn baz() { }
210     }
211 }
212 ```
213
214 In this example, the module `quux` re-exports two public names defined in
215 `foo`.
216
217 Also note that the paths contained in `use` items are relative to the crate
218 root. So, in the previous example, the `use` refers to `quux::foo::{bar,
219 baz}`, and not simply to `foo::{bar, baz}`. This also means that top-level
220 module declarations should be at the crate root if direct usage of the declared
221 modules within `use` items is desired. It is also possible to use `self` and
222 `super` at the beginning of a `use` item to refer to the current and direct
223 parent modules respectively. All rules regarding accessing declared modules in
224 `use` declarations apply to both module declarations and `extern crate`
225 declarations.
226
227 An example of what will and will not work for `use` items:
228
229 ```
230 # #![allow(unused_imports)]
231 use foo::baz::foobaz;    // good: foo is at the root of the crate
232
233 mod foo {
234
235     mod example {
236         pub mod iter {}
237     }
238
239     use foo::example::iter; // good: foo is at crate root
240 //  use example::iter;      // bad:  example is not at the crate root
241     use self::baz::foobaz;  // good: self refers to module 'foo'
242     use foo::bar::foobar;   // good: foo is at crate root
243
244     pub mod bar {
245         pub fn foobar() { }
246     }
247
248     pub mod baz {
249         use super::bar::foobar; // good: super refers to module 'foo'
250         pub fn foobaz() { }
251     }
252 }
253
254 fn main() {}
255 ```
256
257 ## Functions
258
259 A _function item_ defines a sequence of [statements](#statements) and a
260 final [expression](#expressions), along with a name and a set of
261 parameters. Other than a name, all these are optional.
262 Functions are declared with the keyword `fn`. Functions may declare a
263 set of *input* [*variables*](#variables) as parameters, through which the caller
264 passes arguments into the function, and the *output* [*type*](#types)
265 of the value the function will return to its caller on completion.
266
267 A function may also be copied into a first-class *value*, in which case the
268 value has the corresponding [*function type*](#function-types), and can be used
269 otherwise exactly as a function item (with a minor additional cost of calling
270 the function indirectly).
271
272 Every control path in a function logically ends with a `return` expression or a
273 diverging expression. If the outermost block of a function has a
274 value-producing expression in its final-expression position, that expression is
275 interpreted as an implicit `return` expression applied to the final-expression.
276
277 An example of a function:
278
279 ```
280 fn add(x: i32, y: i32) -> i32 {
281     x + y
282 }
283 ```
284
285 As with `let` bindings, function arguments are irrefutable patterns, so any
286 pattern that is valid in a let binding is also valid as an argument.
287
288 ```
289 fn first((value, _): (i32, i32)) -> i32 { value }
290 ```
291
292
293 ### Generic functions
294
295 A _generic function_ allows one or more _parameterized types_ to appear in its
296 signature. Each type parameter must be explicitly declared in an
297 angle-bracket-enclosed and comma-separated list, following the function name.
298
299 ```rust,ignore
300 // foo is generic over A and B
301
302 fn foo<A, B>(x: A, y: B) {
303 ```
304
305 Inside the function signature and body, the name of the type parameter can be
306 used as a type name. [Trait](#traits) bounds can be specified for type parameters
307 to allow methods with that trait to be called on values of that type. This is
308 specified using the `where` syntax:
309
310 ```rust,ignore
311 fn foo<T>(x: T) where T: Debug {
312 ```
313
314 When a generic function is referenced, its type is instantiated based on the
315 context of the reference. For example, calling the `foo` function here:
316
317 ```
318 use std::fmt::Debug;
319
320 fn foo<T>(x: &[T]) where T: Debug {
321     // details elided
322     # ()
323 }
324
325 foo(&[1, 2]);
326 ```
327
328 will instantiate type parameter `T` with `i32`.
329
330 The type parameters can also be explicitly supplied in a trailing
331 [path](#paths) component after the function name. This might be necessary if
332 there is not sufficient context to determine the type parameters. For example,
333 `mem::size_of::<u32>() == 4`.
334
335 ### Diverging functions
336
337 A special kind of function can be declared with a `!` character where the
338 output type would normally be. For example:
339
340 ```
341 fn my_err(s: &str) -> ! {
342     println!("{}", s);
343     panic!();
344 }
345 ```
346
347 We call such functions "diverging" because they never return a value to the
348 caller. Every control path in a diverging function must end with a `panic!()` or
349 a call to another diverging function on every control path. The `!` annotation
350 does *not* denote a type.
351
352 It might be necessary to declare a diverging function because as mentioned
353 previously, the typechecker checks that every control path in a function ends
354 with a [`return`](#return-expressions) or diverging expression. So, if `my_err`
355 were declared without the `!` annotation, the following code would not
356 typecheck:
357
358 ```
359 # fn my_err(s: &str) -> ! { panic!() }
360
361 fn f(i: i32) -> i32 {
362     if i == 42 {
363         return 42;
364     }
365     else {
366         my_err("Bad number!");
367     }
368 }
369 ```
370
371 This will not compile without the `!` annotation on `my_err`, since the `else`
372 branch of the conditional in `f` does not return an `i32`, as required by the
373 signature of `f`. Adding the `!` annotation to `my_err` informs the
374 typechecker that, should control ever enter `my_err`, no further type judgments
375 about `f` need to hold, since control will never resume in any context that
376 relies on those judgments. Thus the return type on `f` only needs to reflect
377 the `if` branch of the conditional.
378
379 ### Extern functions
380
381 Extern functions are part of Rust's foreign function interface, providing the
382 opposite functionality to [external blocks](#external-blocks). Whereas
383 external blocks allow Rust code to call foreign code, extern functions with
384 bodies defined in Rust code _can be called by foreign code_. They are defined
385 in the same way as any other Rust function, except that they have the `extern`
386 modifier.
387
388 ```
389 // Declares an extern fn, the ABI defaults to "C"
390 extern fn new_i32() -> i32 { 0 }
391
392 // Declares an extern fn with "stdcall" ABI
393 extern "stdcall" fn new_i32_stdcall() -> i32 { 0 }
394 ```
395
396 Unlike normal functions, extern fns have type `extern "ABI" fn()`. This is the
397 same type as the functions declared in an extern block.
398
399 ```
400 # extern fn new_i32() -> i32 { 0 }
401 let fptr: extern "C" fn() -> i32 = new_i32;
402 ```
403
404 Extern functions may be called directly from Rust code as Rust uses large,
405 contiguous stack segments like C.
406
407 ## Type aliases
408
409 A _type alias_ defines a new name for an existing [type](#types). Type
410 aliases are declared with the keyword `type`. Every value has a single,
411 specific type, but may implement several different traits, or be compatible with
412 several different type constraints.
413
414 For example, the following defines the type `Point` as a synonym for the type
415 `(u8, u8)`, the type of pairs of unsigned 8 bit integers:
416
417 ```
418 type Point = (u8, u8);
419 let p: Point = (41, 68);
420 ```
421
422 Currently a type alias to an enum type cannot be used to qualify the
423 constructors:
424
425 ```
426 enum E { A }
427 type F = E;
428 let _: F = E::A;  // OK
429 // let _: F = F::A;  // Doesn't work
430 ```
431
432 ## Structs
433
434 A _struct_ is a nominal [struct type](#struct-types) defined with the
435 keyword `struct`.
436
437 An example of a `struct` item and its use:
438
439 ```
440 struct Point {x: i32, y: i32}
441 let p = Point {x: 10, y: 11};
442 let px: i32 = p.x;
443 ```
444
445 A _tuple struct_ is a nominal [tuple type](#tuple-types), also defined with
446 the keyword `struct`. For example:
447
448 ```
449 struct Point(i32, i32);
450 let p = Point(10, 11);
451 let px: i32 = match p { Point(x, _) => x };
452 ```
453
454 A _unit-like struct_ is a struct without any fields, defined by leaving off
455 the list of fields entirely. Such a struct implicitly defines a constant of
456 its type with the same name. For example:
457
458 ```
459 struct Cookie;
460 let c = [Cookie, Cookie {}, Cookie, Cookie {}];
461 ```
462
463 is equivalent to
464
465 ```
466 struct Cookie {}
467 const Cookie: Cookie = Cookie {};
468 let c = [Cookie, Cookie {}, Cookie, Cookie {}];
469 ```
470
471 The precise memory layout of a struct is not specified. One can specify a
472 particular layout using the [`repr` attribute](#ffi-attributes).
473
474 ## Enumerations
475
476 An _enumeration_ is a simultaneous definition of a nominal [enumerated
477 type](#enumerated-types) as well as a set of *constructors*, that can be used
478 to create or pattern-match values of the corresponding enumerated type.
479
480 Enumerations are declared with the keyword `enum`.
481
482 An example of an `enum` item and its use:
483
484 ```
485 enum Animal {
486     Dog,
487     Cat,
488 }
489
490 let mut a: Animal = Animal::Dog;
491 a = Animal::Cat;
492 ```
493
494 Enumeration constructors can have either named or unnamed fields:
495
496 ```rust
497 enum Animal {
498     Dog (String, f64),
499     Cat { name: String, weight: f64 },
500 }
501
502 let mut a: Animal = Animal::Dog("Cocoa".to_string(), 37.2);
503 a = Animal::Cat { name: "Spotty".to_string(), weight: 2.7 };
504 ```
505
506 In this example, `Cat` is a _struct-like enum variant_,
507 whereas `Dog` is simply called an enum variant.
508
509 Each enum value has a _discriminant_ which is an integer associated to it. You
510 can specify it explicitly:
511
512 ```
513 enum Foo {
514     Bar = 123,
515 }
516 ```
517
518 The right hand side of the specification is interpreted as an `isize` value,
519 but the compiler is allowed to use a smaller type in the actual memory layout.
520 The [`repr` attribute](#ffi-attributes) can be added in order to change
521 the type of the right hand side and specify the memory layout.
522
523 If a discriminant isn't specified, they start at zero, and add one for each
524 variant, in order.
525
526 You can cast an enum to get its discriminant:
527
528 ```
529 # enum Foo { Bar = 123 }
530 let x = Foo::Bar as u32; // x is now 123u32
531 ```
532
533 This only works as long as none of the variants have data attached. If
534 it were `Bar(i32)`, this is disallowed.
535
536 ## Constant items
537
538 A *constant item* is a named _constant value_ which is not associated with a
539 specific memory location in the program. Constants are essentially inlined
540 wherever they are used, meaning that they are copied directly into the relevant
541 context when used. References to the same constant are not necessarily
542 guaranteed to refer to the same memory address.
543
544 Constant values must not have destructors, and otherwise permit most forms of
545 data. Constants may refer to the address of other constants, in which case the
546 address will have elided lifetimes where applicable, otherwise â€“ in most cases â€“
547 defaulting to the `static` lifetime. (See below on [static lifetime elision].)
548 The compiler is, however, still at liberty to translate the constant many times,
549 so the address referred to may not be stable.
550
551 [static lifetime elision]: #static-lifetime-elision
552
553 Constants must be explicitly typed. The type may be `bool`, `char`, a number, or
554 a type derived from those primitive types. The derived types are references with
555 the `static` lifetime, fixed-size arrays, tuples, enum variants, and structs.
556
557 ```rust
558 const BIT1: u32 = 1 << 0;
559 const BIT2: u32 = 1 << 1;
560
561 const BITS: [u32; 2] = [BIT1, BIT2];
562 const STRING: &'static str = "bitstring";
563
564 struct BitsNStrings<'a> {
565     mybits: [u32; 2],
566     mystring: &'a str,
567 }
568
569 const BITS_N_STRINGS: BitsNStrings<'static> = BitsNStrings {
570     mybits: BITS,
571     mystring: STRING,
572 };
573 ```
574
575 ## Static items
576
577 A *static item* is similar to a *constant*, except that it represents a precise
578 memory location in the program. A static is never "inlined" at the usage site,
579 and all references to it refer to the same memory location. Static items have
580 the `static` lifetime, which outlives all other lifetimes in a Rust program.
581 Static items may be placed in read-only memory if they do not contain any
582 interior mutability.
583
584 Statics may contain interior mutability through the `UnsafeCell` language item.
585 All access to a static is safe, but there are a number of restrictions on
586 statics:
587
588 * Statics may not contain any destructors.
589 * The types of static values must ascribe to `Sync` to allow thread-safe access.
590 * Statics may not refer to other statics by value, only by reference.
591 * Constants cannot refer to statics.
592
593 Constants should in general be preferred over statics, unless large amounts of
594 data are being stored, or single-address and mutability properties are required.
595
596 ### Mutable statics
597
598 If a static item is declared with the `mut` keyword, then it is allowed to
599 be modified by the program. One of Rust's goals is to make concurrency bugs
600 hard to run into, and this is obviously a very large source of race conditions
601 or other bugs. For this reason, an `unsafe` block is required when either
602 reading or writing a mutable static variable. Care should be taken to ensure
603 that modifications to a mutable static are safe with respect to other threads
604 running in the same process.
605
606 Mutable statics are still very useful, however. They can be used with C
607 libraries and can also be bound from C libraries (in an `extern` block).
608
609 ```rust
610 # fn atomic_add(_: &mut u32, _: u32) -> u32 { 2 }
611
612 static mut LEVELS: u32 = 0;
613
614 // This violates the idea of no shared state, and this doesn't internally
615 // protect against races, so this function is `unsafe`
616 unsafe fn bump_levels_unsafe1() -> u32 {
617     let ret = LEVELS;
618     LEVELS += 1;
619     return ret;
620 }
621
622 // Assuming that we have an atomic_add function which returns the old value,
623 // this function is "safe" but the meaning of the return value may not be what
624 // callers expect, so it's still marked as `unsafe`
625 unsafe fn bump_levels_unsafe2() -> u32 {
626     return atomic_add(&mut LEVELS, 1);
627 }
628 ```
629
630 Mutable statics have the same restrictions as normal statics, except that the
631 type of the value is not required to ascribe to `Sync`.
632
633 #### `'static` lifetime elision
634
635 [Unstable] Both constant and static declarations of reference types have
636 *implicit* `'static` lifetimes unless an explicit lifetime is specified. As
637 such, the constant declarations involving `'static` above may be written
638 without the lifetimes. Returning to our previous example:
639
640 ```rust
641 # #![feature(static_in_const)]
642 const BIT1: u32 = 1 << 0;
643 const BIT2: u32 = 1 << 1;
644
645 const BITS: [u32; 2] = [BIT1, BIT2];
646 const STRING: &str = "bitstring";
647
648 struct BitsNStrings<'a> {
649     mybits: [u32; 2],
650     mystring: &'a str,
651 }
652
653 const BITS_N_STRINGS: BitsNStrings = BitsNStrings {
654     mybits: BITS,
655     mystring: STRING,
656 };
657 ```
658
659 Note that if the `static` or `const` items include function or closure
660 references, which themselves include references, the compiler will first try the
661 standard elision rules ([see discussion in the nomicon][elision-nomicon]). If it
662 is unable to resolve the lifetimes by its usual rules, it will default to using
663 the `'static` lifetime. By way of example:
664
665 [elision-nomicon]: https://doc.rust-lang.org/nomicon/lifetime-elision.html
666
667 ```rust,ignore
668 // Resolved as `fn<'a>(&'a str) -> &'a str`.
669 const RESOLVED_SINGLE: fn(&str) -> &str = ..
670
671 // Resolved as `Fn<'a, 'b, 'c>(&'a Foo, &'b Bar, &'c Baz) -> usize`.
672 const RESOLVED_MULTIPLE: Fn(&Foo, &Bar, &Baz) -> usize = ..
673
674 // There is insufficient information to bound the return reference lifetime
675 // relative to the argument lifetimes, so the signature is resolved as
676 // `Fn(&'static Foo, &'static Bar) -> &'static Baz`.
677 const RESOLVED_STATIC: Fn(&Foo, &Bar) -> &Baz = ..
678 ```
679
680 ### Traits
681
682 A _trait_ describes an abstract interface that types can
683 implement. This interface consists of associated items, which come in
684 three varieties:
685
686 - functions
687 - constants
688 - types
689
690 Associated functions whose first parameter is named `self` are called
691 methods and may be invoked using `.` notation (e.g., `x.foo()`).
692
693 All traits define an implicit type parameter `Self` that refers to
694 "the type that is implementing this interface". Traits may also
695 contain additional type parameters. These type parameters (including
696 `Self`) may be constrained by other traits and so forth as usual.
697
698 Trait bounds on `Self` are considered "supertraits". These are
699 required to be acyclic.  Supertraits are somewhat different from other
700 constraints in that they affect what methods are available in the
701 vtable when the trait is used as a [trait object](#trait-objects).
702
703 Traits are implemented for specific types through separate
704 [implementations](#implementations).
705
706 Consider the following trait:
707
708 ```
709 # type Surface = i32;
710 # type BoundingBox = i32;
711 trait Shape {
712     fn draw(&self, Surface);
713     fn bounding_box(&self) -> BoundingBox;
714 }
715 ```
716
717 This defines a trait with two methods. All values that have
718 [implementations](#implementations) of this trait in scope can have their
719 `draw` and `bounding_box` methods called, using `value.bounding_box()`
720 [syntax](#method-call-expressions).
721
722 Traits can include default implementations of methods, as in:
723
724 ```
725 trait Foo {
726     fn bar(&self);
727     fn baz(&self) { println!("We called baz."); }
728 }
729 ```
730
731 Here the `baz` method has a default implementation, so types that implement
732 `Foo` need only implement `bar`. It is also possible for implementing types
733 to override a method that has a default implementation.
734
735 Type parameters can be specified for a trait to make it generic. These appear
736 after the trait name, using the same syntax used in [generic
737 functions](#generic-functions).
738
739 ```
740 trait Seq<T> {
741     fn len(&self) -> u32;
742     fn elt_at(&self, n: u32) -> T;
743     fn iter<F>(&self, F) where F: Fn(T);
744 }
745 ```
746
747 It is also possible to define associated types for a trait. Consider the
748 following example of a `Container` trait. Notice how the type is available
749 for use in the method signatures:
750
751 ```
752 trait Container {
753     type E;
754     fn empty() -> Self;
755     fn insert(&mut self, Self::E);
756 }
757 ```
758
759 In order for a type to implement this trait, it must not only provide
760 implementations for every method, but it must specify the type `E`. Here's
761 an implementation of `Container` for the standard library type `Vec`:
762
763 ```
764 # trait Container {
765 #     type E;
766 #     fn empty() -> Self;
767 #     fn insert(&mut self, Self::E);
768 # }
769 impl<T> Container for Vec<T> {
770     type E = T;
771     fn empty() -> Vec<T> { Vec::new() }
772     fn insert(&mut self, x: T) { self.push(x); }
773 }
774 ```
775
776 Generic functions may use traits as _bounds_ on their type parameters. This
777 will have two effects:
778
779 - Only types that have the trait may instantiate the parameter.
780 - Within the generic function, the methods of the trait can be
781   called on values that have the parameter's type.
782
783 For example:
784
785 ```
786 # type Surface = i32;
787 # trait Shape { fn draw(&self, Surface); }
788 fn draw_twice<T: Shape>(surface: Surface, sh: T) {
789     sh.draw(surface);
790     sh.draw(surface);
791 }
792 ```
793
794 Traits also define a [trait object](#trait-objects) with the same
795 name as the trait. Values of this type are created by coercing from a
796 pointer of some specific type to a pointer of trait type. For example,
797 `&T` could be coerced to `&Shape` if `T: Shape` holds (and similarly
798 for `Box<T>`). This coercion can either be implicit or
799 [explicit](#type-cast-expressions). Here is an example of an explicit
800 coercion:
801
802 ```
803 trait Shape { }
804 impl Shape for i32 { }
805 let mycircle = 0i32;
806 let myshape: Box<Shape> = Box::new(mycircle) as Box<Shape>;
807 ```
808
809 The resulting value is a box containing the value that was cast, along with
810 information that identifies the methods of the implementation that was used.
811 Values with a trait type can have [methods called](#method-call-expressions) on
812 them, for any method in the trait, and can be used to instantiate type
813 parameters that are bounded by the trait.
814
815 Trait methods may be static, which means that they lack a `self` argument.
816 This means that they can only be called with function call syntax (`f(x)`) and
817 not method call syntax (`obj.f()`). The way to refer to the name of a static
818 method is to qualify it with the trait name, treating the trait name like a
819 module. For example:
820
821 ```
822 trait Num {
823     fn from_i32(n: i32) -> Self;
824 }
825 impl Num for f64 {
826     fn from_i32(n: i32) -> f64 { n as f64 }
827 }
828 let x: f64 = Num::from_i32(42);
829 ```
830
831 Traits may inherit from other traits. Consider the following example:
832
833 ```
834 trait Shape { fn area(&self) -> f64; }
835 trait Circle : Shape { fn radius(&self) -> f64; }
836 ```
837
838 The syntax `Circle : Shape` means that types that implement `Circle` must also
839 have an implementation for `Shape`. Multiple supertraits are separated by `+`,
840 `trait Circle : Shape + PartialEq { }`. In an implementation of `Circle` for a
841 given type `T`, methods can refer to `Shape` methods, since the typechecker
842 checks that any type with an implementation of `Circle` also has an
843 implementation of `Shape`:
844
845 ```rust
846 struct Foo;
847
848 trait Shape { fn area(&self) -> f64; }
849 trait Circle : Shape { fn radius(&self) -> f64; }
850 impl Shape for Foo {
851     fn area(&self) -> f64 {
852         0.0
853     }
854 }
855 impl Circle for Foo {
856     fn radius(&self) -> f64 {
857         println!("calling area: {}", self.area());
858
859         0.0
860     }
861 }
862
863 let c = Foo;
864 c.radius();
865 ```
866
867 In type-parameterized functions, methods of the supertrait may be called on
868 values of subtrait-bound type parameters. Referring to the previous example of
869 `trait Circle : Shape`:
870
871 ```
872 # trait Shape { fn area(&self) -> f64; }
873 # trait Circle : Shape { fn radius(&self) -> f64; }
874 fn radius_times_area<T: Circle>(c: T) -> f64 {
875     // `c` is both a Circle and a Shape
876     c.radius() * c.area()
877 }
878 ```
879
880 Likewise, supertrait methods may also be called on trait objects.
881
882 ```{.ignore}
883 # trait Shape { fn area(&self) -> f64; }
884 # trait Circle : Shape { fn radius(&self) -> f64; }
885 # impl Shape for i32 { fn area(&self) -> f64 { 0.0 } }
886 # impl Circle for i32 { fn radius(&self) -> f64 { 0.0 } }
887 # let mycircle = 0i32;
888 let mycircle = Box::new(mycircle) as Box<Circle>;
889 let nonsense = mycircle.radius() * mycircle.area();
890 ```
891
892 ### Implementations
893
894 An _implementation_ is an item that implements a [trait](#traits) for a
895 specific type.
896
897 Implementations are defined with the keyword `impl`.
898
899 ```
900 # #[derive(Copy, Clone)]
901 # struct Point {x: f64, y: f64};
902 # type Surface = i32;
903 # struct BoundingBox {x: f64, y: f64, width: f64, height: f64};
904 # trait Shape { fn draw(&self, Surface); fn bounding_box(&self) -> BoundingBox; }
905 # fn do_draw_circle(s: Surface, c: Circle) { }
906 struct Circle {
907     radius: f64,
908     center: Point,
909 }
910
911 impl Copy for Circle {}
912
913 impl Clone for Circle {
914     fn clone(&self) -> Circle { *self }
915 }
916
917 impl Shape for Circle {
918     fn draw(&self, s: Surface) { do_draw_circle(s, *self); }
919     fn bounding_box(&self) -> BoundingBox {
920         let r = self.radius;
921         BoundingBox {
922             x: self.center.x - r,
923             y: self.center.y - r,
924             width: 2.0 * r,
925             height: 2.0 * r,
926         }
927     }
928 }
929 ```
930
931 It is possible to define an implementation without referring to a trait. The
932 methods in such an implementation can only be used as direct calls on the values
933 of the type that the implementation targets. In such an implementation, the
934 trait type and `for` after `impl` are omitted. Such implementations are limited
935 to nominal types (enums, structs, trait objects), and the implementation must
936 appear in the same crate as the `self` type:
937
938 ```
939 struct Point {x: i32, y: i32}
940
941 impl Point {
942     fn log(&self) {
943         println!("Point is at ({}, {})", self.x, self.y);
944     }
945 }
946
947 let my_point = Point {x: 10, y:11};
948 my_point.log();
949 ```
950
951 When a trait _is_ specified in an `impl`, all methods declared as part of the
952 trait must be implemented, with matching types and type parameter counts.
953
954 An implementation can take type parameters, which can be different from the
955 type parameters taken by the trait it implements. Implementation parameters
956 are written after the `impl` keyword.
957
958 ```
959 # trait Seq<T> { fn dummy(&self, _: T) { } }
960 impl<T> Seq<T> for Vec<T> {
961     /* ... */
962 }
963 impl Seq<bool> for u32 {
964     /* Treat the integer as a sequence of bits */
965 }
966 ```
967
968 ### External blocks
969
970 External blocks form the basis for Rust's foreign function interface.
971 Declarations in an external block describe symbols in external, non-Rust
972 libraries.
973
974 Functions within external blocks are declared in the same way as other Rust
975 functions, with the exception that they may not have a body and are instead
976 terminated by a semicolon.
977
978 Functions within external blocks may be called by Rust code, just like
979 functions defined in Rust. The Rust compiler automatically translates between
980 the Rust ABI and the foreign ABI.
981
982 Functions within external blocks may be variadic by specifying `...` after one
983 or more named arguments in the argument list:
984
985 ```ignore
986 extern {
987     fn foo(x: i32, ...);
988 }
989 ```
990
991 A number of [attributes](#ffi-attributes) control the behavior of external blocks.
992
993 By default external blocks assume that the library they are calling uses the
994 standard C ABI on the specific platform. Other ABIs may be specified using an
995 `abi` string, as shown here:
996
997 ```ignore
998 // Interface to the Windows API
999 extern "stdcall" { }
1000 ```
1001
1002 There are three ABI strings which are cross-platform, and which all compilers
1003 are guaranteed to support:
1004
1005 * `extern "Rust"` -- The default ABI when you write a normal `fn foo()` in any
1006   Rust code.
1007 * `extern "C"` -- This is the same as `extern fn foo()`; whatever the default
1008   your C compiler supports.
1009 * `extern "system"` -- Usually the same as `extern "C"`, except on Win32, in
1010   which case it's `"stdcall"`, or what you should use to link to the Windows API
1011   itself
1012
1013 There are also some platform-specific ABI strings:
1014
1015 * `extern "cdecl"` -- The default for x86\_32 C code.
1016 * `extern "stdcall"` -- The default for the Win32 API on x86\_32.
1017 * `extern "win64"` -- The default for C code on x86\_64 Windows.
1018 * `extern "sysv64"` -- The default for C code on non-Windows x86\_64.
1019 * `extern "aapcs"` -- The default for ARM.
1020 * `extern "fastcall"` -- The `fastcall` ABI -- corresponds to MSVC's
1021   `__fastcall` and GCC and clang's `__attribute__((fastcall))`
1022 * `extern "vectorcall"` -- The `vectorcall` ABI -- corresponds to MSVC's
1023   `__vectorcall` and clang's `__attribute__((vectorcall))`
1024
1025 Finally, there are some rustc-specific ABI strings:
1026
1027 * `extern "rust-intrinsic"` -- The ABI of rustc intrinsics.
1028 * `extern "rust-call"` -- The ABI of the Fn::call trait functions.
1029 * `extern "platform-intrinsic"` -- Specific platform intrinsics -- like, for
1030   example, `sqrt` -- have this ABI. You should never have to deal with it.
1031
1032 The `link` attribute allows the name of the library to be specified. When
1033 specified the compiler will attempt to link against the native library of the
1034 specified name.
1035
1036 ```{.ignore}
1037 #[link(name = "crypto")]
1038 extern { }
1039 ```
1040
1041 The type of a function declared in an extern block is `extern "abi" fn(A1, ...,
1042 An) -> R`, where `A1...An` are the declared types of its arguments and `R` is
1043 the declared return type.
1044
1045 It is valid to add the `link` attribute on an empty extern block. You can use
1046 this to satisfy the linking requirements of extern blocks elsewhere in your code
1047 (including upstream crates) instead of adding the attribute to each extern block.