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