3 An _item_ is a component of a crate. Items are organized within a crate by a
4 nested set of [modules]. Every crate has a single "outermost"
5 anonymous module; all further items within the crate have [paths]
6 within the module tree of the crate.
11 Items are entirely determined at compile-time, generally remain fixed during
12 execution, and may reside in read-only memory.
14 There are several kinds of item:
16 * [`extern crate` declarations](#extern-crate-declarations)
17 * [`use` declarations](#use-declarations)
19 * [function definitions](#functions)
20 * [`extern` blocks](#external-blocks)
21 * [type definitions](#type-aliases)
22 * [struct definitions](#structs)
23 * [enumeration definitions](#enumerations)
24 * [union definitions](#unions)
25 * [constant items](#constant-items)
26 * [static items](#static-items)
27 * [trait definitions](#traits)
28 * [implementations](#implementations)
30 Some items form an implicit scope for the declaration of sub-items. In other
31 words, within a function or module, declarations of items can (in many cases)
32 be mixed with the statements, control blocks, and similar artifacts that
33 otherwise compose the item body. The meaning of these scoped items is the same
34 as if the item was declared outside the scope — it is still a static item
35 — except that the item's *path name* within the module namespace is
36 qualified by the name of the enclosing item, or is private to the enclosing
37 item (in the case of functions). The grammar specifies the exact locations in
38 which sub-item declarations may appear.
42 All items except modules, constants and statics may be *parameterized* by type.
43 Type parameters are given as a comma-separated list of identifiers enclosed in
44 angle brackets (`<...>`), after the name of the item and before its definition.
45 The type parameters of an item are considered "part of the name", not part of
46 the type of the item. A referencing [path] must (in principle) provide
47 type arguments as a list of comma-separated types enclosed within angle
48 brackets, in order to refer to the type-parameterized item. In practice, the
49 type-inference system can usually infer such argument types from context. There
50 are no general type-parametric types, only type-parametric items. That is, Rust
51 has no notion of type abstraction: there are no higher-ranked (or "forall") types
52 abstracted over other types, though higher-ranked types do exist for lifetimes.
58 A module is a container for zero or more [items].
62 A _module item_ is a module, surrounded in braces, named, and prefixed with the
63 keyword `mod`. A module item introduces a new, named module into the tree of
64 modules making up a crate. Modules can nest arbitrarily.
66 An example of a module:
70 type Complex = (f64, f64);
71 fn sin(f: f64) -> f64 {
75 fn cos(f: f64) -> f64 {
79 fn tan(f: f64) -> f64 {
86 Modules and types share the same namespace. Declaring a named type with
87 the same name as a module in scope is forbidden: that is, a type definition,
88 trait, struct, enumeration, or type parameter can't shadow the name of a module
89 in scope, or vice versa.
91 A module without a body is loaded from an external file, by default with the
92 same name as the module, plus the `.rs` extension. When a nested submodule is
93 loaded from an external file, it is loaded from a subdirectory path that
94 mirrors the module hierarchy.
97 // Load the `vec` module from `vec.rs`
101 // Load the `local_data` module from `thread/local_data.rs`
102 // or `thread/local_data/mod.rs`.
107 The directories and files used for loading external file modules can be
108 influenced with the `path` attribute.
111 #[path = "thread_files"]
113 // Load the `local_data` module from `thread_files/tls.rs`
119 ### Extern crate declarations
121 An _`extern crate` declaration_ specifies a dependency on an external crate.
122 The external crate is then bound into the declaring scope as the `ident`
123 provided in the `extern_crate_decl`.
125 The external crate is resolved to a specific `soname` at compile time, and a
126 runtime linkage requirement to that `soname` is passed to the linker for
127 loading at runtime. The `soname` is resolved at compile time by scanning the
128 compiler's library path and matching the optional `crateid` provided against
129 the `crateid` attributes that were declared on the external crate when it was
130 compiled. If no `crateid` is provided, a default `name` attribute is assumed,
131 equal to the `ident` given in the `extern_crate_decl`.
133 Three examples of `extern crate` declarations:
138 extern crate std; // equivalent to: extern crate std as std;
140 extern crate std as ruststd; // linking to 'std' under another name
143 When naming Rust crates, hyphens are disallowed. However, Cargo packages may
144 make use of them. In such case, when `Cargo.toml` doesn't specify a crate name,
145 Cargo will transparently replace `-` with `_` (Refer to [RFC 940] for more
151 // Importing the Cargo package hello-world
152 extern crate hello_world; // hyphen replaced with an underscore
155 [RFC 940]: https://github.com/rust-lang/rfcs/blob/master/text/0940-hyphens-considered-harmful.md
159 A _use declaration_ creates one or more local name bindings synonymous with
160 some other [path]. Usually a `use` declaration is used to shorten the
161 path required to refer to a module item. These declarations may appear in
162 [modules] and [blocks], usually at the top.
166 [blocks]: ../grammar.html#block-expressions
168 > **Note**: Unlike in many languages,
169 > `use` declarations in Rust do *not* declare linkage dependency with external crates.
170 > Rather, [`extern crate` declarations](#extern-crate-declarations) declare linkage dependencies.
172 Use declarations support a number of convenient shortcuts:
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 * Simultaneously binding a list of paths differing only in their final element
177 and their immediate parent module, using the `self` keyword, such as
178 `use a::b::{self, c, d};`
179 * Rebinding the target name as a new local name, using the syntax `use p::q::r
180 as x;`. This can also be used with the last two features: `use a::b::{self as
182 * Binding all paths matching a given prefix, using the asterisk wildcard syntax
185 An example of `use` declarations:
188 use std::option::Option::{Some, None};
189 use std::collections::hash_map::{self, HashMap};
192 fn bar(map1: HashMap<String, usize>, map2: hash_map::HashMap<String, usize>){}
195 // Equivalent to 'foo(vec![std::option::Option::Some(1.0f64),
196 // std::option::Option::None]);'
197 foo(vec![Some(1.0f64), None]);
199 // Both `hash_map` and `HashMap` are in scope.
200 let map1 = HashMap::new();
201 let map2 = hash_map::HashMap::new();
206 Like items, `use` declarations are private to the containing module, by
207 default. Also like items, a `use` declaration can be public, if qualified by
208 the `pub` keyword. Such a `use` declaration serves to _re-export_ a name. A
209 public `use` declaration can therefore _redirect_ some public name to a
210 different target definition: even a definition with a private canonical path,
211 inside a different module. If a sequence of such redirections form a cycle or
212 cannot be resolved unambiguously, they represent a compile-time error.
214 An example of re-exporting:
219 pub use quux::foo::{bar, baz};
228 In this example, the module `quux` re-exports two public names defined in
231 Also note that the paths contained in `use` items are relative to the crate
232 root. So, in the previous example, the `use` refers to `quux::foo::{bar,
233 baz}`, and not simply to `foo::{bar, baz}`. This also means that top-level
234 module declarations should be at the crate root if direct usage of the declared
235 modules within `use` items is desired. It is also possible to use `self` and
236 `super` at the beginning of a `use` item to refer to the current and direct
237 parent modules respectively. All rules regarding accessing declared modules in
238 `use` declarations apply to both module declarations and `extern crate`
241 An example of what will and will not work for `use` items:
244 # #![allow(unused_imports)]
245 use foo::baz::foobaz; // good: foo is at the root of the crate
253 use foo::example::iter; // good: foo is at crate root
254 // use example::iter; // bad: example is not at the crate root
255 use self::baz::foobaz; // good: self refers to module 'foo'
256 use foo::bar::foobar; // good: foo is at crate root
263 use super::bar::foobar; // good: super refers to module 'foo'
273 A _function item_ defines a sequence of [statements] and a
274 final [expression], along with a name and a set of
275 parameters. Other than a name, all these are optional.
276 Functions are declared with the keyword `fn`. Functions may declare a
277 set of *input* [*variables*][variables] as parameters, through which the caller
278 passes arguments into the function, and the *output* [*type*][type]
279 of the value the function will return to its caller on completion.
281 [statements]: statements.html
282 [expression]: expressions.html
283 [variables]: variables.html
286 A function may also be copied into a first-class *value*, in which case the
287 value has the corresponding [*function type*][function type], and can be used
288 otherwise exactly as a function item (with a minor additional cost of calling
289 the function indirectly).
291 [function type]: types.html#function-types
293 Every control path in a function logically ends with a `return` expression or a
294 diverging expression. If the outermost block of a function has a
295 value-producing expression in its final-expression position, that expression is
296 interpreted as an implicit `return` expression applied to the final-expression.
298 An example of a function:
301 fn add(x: i32, y: i32) -> i32 {
306 As with `let` bindings, function arguments are irrefutable patterns, so any
307 pattern that is valid in a let binding is also valid as an argument.
310 fn first((value, _): (i32, i32)) -> i32 { value }
314 ### Generic functions
316 A _generic function_ allows one or more _parameterized types_ to appear in its
317 signature. Each type parameter must be explicitly declared in an
318 angle-bracket-enclosed and comma-separated list, following the function name.
321 // foo is generic over A and B
323 fn foo<A, B>(x: A, y: B) {
326 Inside the function signature and body, the name of the type parameter can be
327 used as a type name. [Trait](#traits) bounds can be specified for type parameters
328 to allow methods with that trait to be called on values of that type. This is
329 specified using the `where` syntax:
332 fn foo<T>(x: T) where T: Debug {
335 When a generic function is referenced, its type is instantiated based on the
336 context of the reference. For example, calling the `foo` function here:
341 fn foo<T>(x: &[T]) where T: Debug {
349 will instantiate type parameter `T` with `i32`.
351 The type parameters can also be explicitly supplied in a trailing
352 [path] component after the function name. This might be necessary if
353 there is not sufficient context to determine the type parameters. For example,
354 `mem::size_of::<u32>() == 4`.
358 ### Diverging functions
360 A special kind of function can be declared with a `!` character where the
361 output type would normally be. For example:
364 fn my_err(s: &str) -> ! {
370 We call such functions "diverging" because they never return a value to the
371 caller. Every control path in a diverging function must end with a `panic!()`,
372 a loop expression without an associated break expression, or a call to another
373 diverging function on every control path. The `!` annotation does *not* denote
376 It might be necessary to declare a diverging function because as mentioned
377 previously, the typechecker checks that every control path in a function ends
378 with a [`return`] or diverging expression. So, if `my_err`
379 were declared without the `!` annotation, the following code would not
382 [`return`]: expressions.html#return-expressions
385 # fn my_err(s: &str) -> ! { panic!() }
387 fn f(i: i32) -> i32 {
392 my_err("Bad number!");
397 This will not compile without the `!` annotation on `my_err`, since the `else`
398 branch of the conditional in `f` does not return an `i32`, as required by the
399 signature of `f`. Adding the `!` annotation to `my_err` informs the
400 typechecker that, should control ever enter `my_err`, no further type judgments
401 about `f` need to hold, since control will never resume in any context that
402 relies on those judgments. Thus the return type on `f` only needs to reflect
403 the `if` branch of the conditional.
407 Extern functions are part of Rust's foreign function interface, providing the
408 opposite functionality to [external blocks](#external-blocks). Whereas
409 external blocks allow Rust code to call foreign code, extern functions with
410 bodies defined in Rust code _can be called by foreign code_. They are defined
411 in the same way as any other Rust function, except that they have the `extern`
415 // Declares an extern fn, the ABI defaults to "C"
416 extern fn new_i32() -> i32 { 0 }
418 // Declares an extern fn with "stdcall" ABI
419 # #[cfg(target_arch = "x86_64")]
420 extern "stdcall" fn new_i32_stdcall() -> i32 { 0 }
423 Unlike normal functions, extern fns have type `extern "ABI" fn()`. This is the
424 same type as the functions declared in an extern block.
427 # extern fn new_i32() -> i32 { 0 }
428 let fptr: extern "C" fn() -> i32 = new_i32;
431 Extern functions may be called directly from Rust code as Rust uses large,
432 contiguous stack segments like C.
436 A _type alias_ defines a new name for an existing [type]. Type
437 aliases are declared with the keyword `type`. Every value has a single,
438 specific type, but may implement several different traits, or be compatible with
439 several different type constraints.
443 For example, the following defines the type `Point` as a synonym for the type
444 `(u8, u8)`, the type of pairs of unsigned 8 bit integers:
447 type Point = (u8, u8);
448 let p: Point = (41, 68);
451 A type alias to an enum type cannot be used to qualify the constructors:
456 let _: F = E::A; // OK
457 // let _: F = F::A; // Doesn't work
462 A _struct_ is a nominal [struct type] defined with the
465 An example of a `struct` item and its use:
468 struct Point {x: i32, y: i32}
469 let p = Point {x: 10, y: 11};
473 A _tuple struct_ is a nominal [tuple type], also defined with
474 the keyword `struct`. For example:
476 [struct type]: types.html#struct-types
477 [tuple type]: types.html#tuple-types
480 struct Point(i32, i32);
481 let p = Point(10, 11);
482 let px: i32 = match p { Point(x, _) => x };
485 A _unit-like struct_ is a struct without any fields, defined by leaving off
486 the list of fields entirely. Such a struct implicitly defines a constant of
487 its type with the same name. For example:
491 let c = [Cookie, Cookie {}, Cookie, Cookie {}];
498 const Cookie: Cookie = Cookie {};
499 let c = [Cookie, Cookie {}, Cookie, Cookie {}];
502 The precise memory layout of a struct is not specified. One can specify a
503 particular layout using the [`repr` attribute].
505 [`repr` attribute]: attributes.html#ffi-attributes
509 An _enumeration_ is a simultaneous definition of a nominal [enumerated
510 type] as well as a set of *constructors*, that can be used
511 to create or pattern-match values of the corresponding enumerated type.
513 [enumerated type]: types.html#enumerated-types
515 Enumerations are declared with the keyword `enum`.
517 An example of an `enum` item and its use:
525 let mut a: Animal = Animal::Dog;
529 Enumeration constructors can have either named or unnamed fields:
534 Cat { name: String, weight: f64 },
537 let mut a: Animal = Animal::Dog("Cocoa".to_string(), 37.2);
538 a = Animal::Cat { name: "Spotty".to_string(), weight: 2.7 };
541 In this example, `Cat` is a _struct-like enum variant_,
542 whereas `Dog` is simply called an enum variant.
544 Each enum value has a _discriminant_ which is an integer associated to it. You
545 can specify it explicitly:
553 The right hand side of the specification is interpreted as an `isize` value,
554 but the compiler is allowed to use a smaller type in the actual memory layout.
555 The [`repr` attribute] can be added in order to change
556 the type of the right hand side and specify the memory layout.
558 [`repr` attribute]: attributes.html#ffi-attributes
560 If a discriminant isn't specified, they start at zero, and add one for each
563 You can cast an enum to get its discriminant:
566 # enum Foo { Bar = 123 }
567 let x = Foo::Bar as u32; // x is now 123u32
570 This only works as long as none of the variants have data attached. If
571 it were `Bar(i32)`, this is disallowed.
575 A union declaration uses the same syntax as a struct declaration, except with
576 `union` in place of `struct`.
586 The key property of unions is that all fields of a union share common storage.
587 As a result writes to one field of a union can overwrite its other fields,
588 and size of a union is determined by the size of its largest field.
590 A value of a union type can be created using the same syntax that is used for
591 struct types, except that it must specify exactly one field:
594 # union MyUnion { f1: u32, f2: f32 }
596 let u = MyUnion { f1: 1 };
599 The expression above creates a value of type `MyUnion` with active field `f1`.
600 Active field of a union can be accessed using the same syntax as struct fields:
606 Inactive fields can be accessed as well (using the same syntax) if they are
607 sufficiently layout compatible with the
608 current value kept by the union. Reading incompatible fields results in
610 However, the active field is not generally known statically, so all reads of
611 union fields have to be placed in `unsafe` blocks.
614 # union MyUnion { f1: u32, f2: f32 }
615 # let u = MyUnion { f1: 1 };
622 Writes to `Copy` union fields do not require reads for running destructors,
623 so these writes don't have to be placed in `unsafe` blocks
626 # union MyUnion { f1: u32, f2: f32 }
627 # let mut u = MyUnion { f1: 1 };
632 Commonly, code using unions will provide safe wrappers around unsafe
633 union field accesses.
635 Another way to access union fields is to use pattern matching.
636 Pattern matching on union fields uses the same syntax as struct patterns,
637 except that the pattern must specify exactly one field.
638 Since pattern matching accesses potentially inactive fields it has
639 to be placed in `unsafe` blocks as well.
642 # union MyUnion { f1: u32, f2: f32 }
647 MyUnion { f1: 10 } => { println!("ten"); }
648 MyUnion { f2 } => { println!("{}", f2); }
654 Pattern matching may match a union as a field of a larger structure. In
655 particular, when using a Rust union to implement a C tagged union via FFI, this
656 allows matching on the tag and the corresponding field simultaneously:
674 fn is_zero(v: Value) -> bool {
677 Value { tag: I, u: U { i: 0 } } => true,
678 Value { tag: F, u: U { f: 0.0 } } => true,
685 Since union fields share common storage, gaining write access to one
686 field of a union can give write access to all its remaining fields.
687 Borrow checking rules have to be adjusted to account for this fact.
688 As a result, if one field of a union is borrowed, all its remaining fields
689 are borrowed as well for the same lifetime.
692 // ERROR: cannot borrow `u` (via `u.f2`) as mutable more than once at a time
694 let mut u = MyUnion { f1: 1 };
697 ---- first mutable borrow occurs here (via `u.f1`)
699 ^^^^ second mutable borrow occurs here (via `u.f2`)
702 - first borrow ends here
703 assert_eq!(unsafe { u.f1 }, 5);
707 As you could see, in many aspects (except for layouts, safety and ownership)
708 unions behave exactly like structs, largely as a consequence of inheriting their
709 syntactic shape from structs.
710 This is also true for many unmentioned aspects of Rust language (such as
711 privacy, name resolution, type inference, generics, trait implementations,
712 inherent implementations, coherence, pattern checking, etc etc etc).
714 More detailed specification for unions, including unstable bits, can be found in
715 [RFC 1897 "Unions v1.2"](https://github.com/rust-lang/rfcs/pull/1897).
719 A *constant item* is a named _[constant value]_ which is not associated with a
720 specific memory location in the program. Constants are essentially inlined
721 wherever they are used, meaning that they are copied directly into the relevant
722 context when used. References to the same constant are not necessarily
723 guaranteed to refer to the same memory address.
725 [constant value]: expressions.html#constant-expressions
727 Constant values must not have destructors, and otherwise permit most forms of
728 data. Constants may refer to the address of other constants, in which case the
729 address will have elided lifetimes where applicable, otherwise – in most cases –
730 defaulting to the `static` lifetime. (See below on [static lifetime elision].)
731 The compiler is, however, still at liberty to translate the constant many times,
732 so the address referred to may not be stable.
734 [static lifetime elision]: #static-lifetime-elision
736 Constants must be explicitly typed. The type may be `bool`, `char`, a number, or
737 a type derived from those primitive types. The derived types are references with
738 the `static` lifetime, fixed-size arrays, tuples, enum variants, and structs.
741 const BIT1: u32 = 1 << 0;
742 const BIT2: u32 = 1 << 1;
744 const BITS: [u32; 2] = [BIT1, BIT2];
745 const STRING: &'static str = "bitstring";
747 struct BitsNStrings<'a> {
752 const BITS_N_STRINGS: BitsNStrings<'static> = BitsNStrings {
760 A *static item* is similar to a *constant*, except that it represents a precise
761 memory location in the program. A static is never "inlined" at the usage site,
762 and all references to it refer to the same memory location. Static items have
763 the `static` lifetime, which outlives all other lifetimes in a Rust program.
764 Static items may be placed in read-only memory if they do not contain any
767 Statics may contain interior mutability through the `UnsafeCell` language item.
768 All access to a static is safe, but there are a number of restrictions on
771 * Statics may not contain any destructors.
772 * The types of static values must ascribe to `Sync` to allow thread-safe access.
773 * Statics may not refer to other statics by value, only by reference.
774 * Constants cannot refer to statics.
776 Constants should in general be preferred over statics, unless large amounts of
777 data are being stored, or single-address and mutability properties are required.
781 If a static item is declared with the `mut` keyword, then it is allowed to
782 be modified by the program. One of Rust's goals is to make concurrency bugs
783 hard to run into, and this is obviously a very large source of race conditions
784 or other bugs. For this reason, an `unsafe` block is required when either
785 reading or writing a mutable static variable. Care should be taken to ensure
786 that modifications to a mutable static are safe with respect to other threads
787 running in the same process.
789 Mutable statics are still very useful, however. They can be used with C
790 libraries and can also be bound from C libraries (in an `extern` block).
793 # fn atomic_add(_: &mut u32, _: u32) -> u32 { 2 }
795 static mut LEVELS: u32 = 0;
797 // This violates the idea of no shared state, and this doesn't internally
798 // protect against races, so this function is `unsafe`
799 unsafe fn bump_levels_unsafe1() -> u32 {
805 // Assuming that we have an atomic_add function which returns the old value,
806 // this function is "safe" but the meaning of the return value may not be what
807 // callers expect, so it's still marked as `unsafe`
808 unsafe fn bump_levels_unsafe2() -> u32 {
809 return atomic_add(&mut LEVELS, 1);
813 Mutable statics have the same restrictions as normal statics, except that the
814 type of the value is not required to ascribe to `Sync`.
816 #### `'static` lifetime elision
818 Both constant and static declarations of reference types have *implicit*
819 `'static` lifetimes unless an explicit lifetime is specified. As such, the
820 constant declarations involving `'static` above may be written without the
821 lifetimes. Returning to our previous example:
824 const BIT1: u32 = 1 << 0;
825 const BIT2: u32 = 1 << 1;
827 const BITS: [u32; 2] = [BIT1, BIT2];
828 const STRING: &str = "bitstring";
830 struct BitsNStrings<'a> {
835 const BITS_N_STRINGS: BitsNStrings = BitsNStrings {
841 Note that if the `static` or `const` items include function or closure
842 references, which themselves include references, the compiler will first try the
843 standard elision rules ([see discussion in the nomicon][elision-nomicon]). If it
844 is unable to resolve the lifetimes by its usual rules, it will default to using
845 the `'static` lifetime. By way of example:
847 [elision-nomicon]: ../nomicon/lifetime-elision.html
850 // Resolved as `fn<'a>(&'a str) -> &'a str`.
851 const RESOLVED_SINGLE: fn(&str) -> &str = ..
853 // Resolved as `Fn<'a, 'b, 'c>(&'a Foo, &'b Bar, &'c Baz) -> usize`.
854 const RESOLVED_MULTIPLE: Fn(&Foo, &Bar, &Baz) -> usize = ..
856 // There is insufficient information to bound the return reference lifetime
857 // relative to the argument lifetimes, so the signature is resolved as
858 // `Fn(&'static Foo, &'static Bar) -> &'static Baz`.
859 const RESOLVED_STATIC: Fn(&Foo, &Bar) -> &Baz = ..
864 A _trait_ describes an abstract interface that types can
865 implement. This interface consists of associated items, which come in
869 - [constants](#associated-constants)
872 Associated functions whose first parameter is named `self` are called
873 methods and may be invoked using `.` notation (e.g., `x.foo()`).
875 All traits define an implicit type parameter `Self` that refers to
876 "the type that is implementing this interface". Traits may also
877 contain additional type parameters. These type parameters (including
878 `Self`) may be constrained by other traits and so forth as usual.
880 Trait bounds on `Self` are considered "supertraits". These are
881 required to be acyclic. Supertraits are somewhat different from other
882 constraints in that they affect what methods are available in the
883 vtable when the trait is used as a [trait object].
885 Traits are implemented for specific types through separate
888 Consider the following trait:
891 # type Surface = i32;
892 # type BoundingBox = i32;
894 fn draw(&self, Surface);
895 fn bounding_box(&self) -> BoundingBox;
899 This defines a trait with two methods. All values that have
900 [implementations] of this trait in scope can have their
901 `draw` and `bounding_box` methods called, using `value.bounding_box()`
904 [trait object]: types.html#trait-objects
905 [implementations]: #implementations
906 [syntax]: expressions.html#method-call-expressions
908 Traits can include default implementations of methods, as in:
913 fn baz(&self) { println!("We called baz."); }
917 Here the `baz` method has a default implementation, so types that implement
918 `Foo` need only implement `bar`. It is also possible for implementing types
919 to override a method that has a default implementation.
921 Type parameters can be specified for a trait to make it generic. These appear
922 after the trait name, using the same syntax used in [generic
923 functions](#generic-functions).
927 fn len(&self) -> u32;
928 fn elt_at(&self, n: u32) -> T;
929 fn iter<F>(&self, F) where F: Fn(T);
933 It is also possible to define associated types for a trait. Consider the
934 following example of a `Container` trait. Notice how the type is available
935 for use in the method signatures:
941 fn insert(&mut self, Self::E);
945 In order for a type to implement this trait, it must not only provide
946 implementations for every method, but it must specify the type `E`. Here's
947 an implementation of `Container` for the standard library type `Vec`:
952 # fn empty() -> Self;
953 # fn insert(&mut self, Self::E);
955 impl<T> Container for Vec<T> {
957 fn empty() -> Vec<T> { Vec::new() }
958 fn insert(&mut self, x: T) { self.push(x); }
962 Generic functions may use traits as _bounds_ on their type parameters. This
963 will have two effects:
965 - Only types that have the trait may instantiate the parameter.
966 - Within the generic function, the methods of the trait can be
967 called on values that have the parameter's type.
972 # type Surface = i32;
973 # trait Shape { fn draw(&self, Surface); }
974 fn draw_twice<T: Shape>(surface: Surface, sh: T) {
980 Traits also define a [trait object] with the same
981 name as the trait. Values of this type are created by coercing from a
982 pointer of some specific type to a pointer of trait type. For example,
983 `&T` could be coerced to `&Shape` if `T: Shape` holds (and similarly
984 for `Box<T>`). This coercion can either be implicit or
985 [explicit]. Here is an example of an explicit
988 [trait object]: types.html#trait-objects
989 [explicit]: expressions.html#type-cast-expressions
993 impl Shape for i32 { }
995 let myshape: Box<Shape> = Box::new(mycircle) as Box<Shape>;
998 The resulting value is a box containing the value that was cast, along with
999 information that identifies the methods of the implementation that was used.
1000 Values with a trait type can have [methods called] on
1001 them, for any method in the trait, and can be used to instantiate type
1002 parameters that are bounded by the trait.
1004 [methods called]: expressions.html#method-call-expressions
1006 Trait methods may be static, which means that they lack a `self` argument.
1007 This means that they can only be called with function call syntax (`f(x)`) and
1008 not method call syntax (`obj.f()`). The way to refer to the name of a static
1009 method is to qualify it with the trait name, treating the trait name like a
1010 module. For example:
1014 fn from_i32(n: i32) -> Self;
1017 fn from_i32(n: i32) -> f64 { n as f64 }
1019 let x: f64 = Num::from_i32(42);
1022 Traits may inherit from other traits. Consider the following example:
1025 trait Shape { fn area(&self) -> f64; }
1026 trait Circle : Shape { fn radius(&self) -> f64; }
1029 The syntax `Circle : Shape` means that types that implement `Circle` must also
1030 have an implementation for `Shape`. Multiple supertraits are separated by `+`,
1031 `trait Circle : Shape + PartialEq { }`. In an implementation of `Circle` for a
1032 given type `T`, methods can refer to `Shape` methods, since the typechecker
1033 checks that any type with an implementation of `Circle` also has an
1034 implementation of `Shape`:
1039 trait Shape { fn area(&self) -> f64; }
1040 trait Circle : Shape { fn radius(&self) -> f64; }
1041 impl Shape for Foo {
1042 fn area(&self) -> f64 {
1046 impl Circle for Foo {
1047 fn radius(&self) -> f64 {
1048 println!("calling area: {}", self.area());
1058 In type-parameterized functions, methods of the supertrait may be called on
1059 values of subtrait-bound type parameters. Referring to the previous example of
1060 `trait Circle : Shape`:
1063 # trait Shape { fn area(&self) -> f64; }
1064 # trait Circle : Shape { fn radius(&self) -> f64; }
1065 fn radius_times_area<T: Circle>(c: T) -> f64 {
1066 // `c` is both a Circle and a Shape
1067 c.radius() * c.area()
1071 Likewise, supertrait methods may also be called on trait objects.
1074 # trait Shape { fn area(&self) -> f64; }
1075 # trait Circle : Shape { fn radius(&self) -> f64; }
1076 # impl Shape for i32 { fn area(&self) -> f64 { 0.0 } }
1077 # impl Circle for i32 { fn radius(&self) -> f64 { 0.0 } }
1078 # let mycircle = 0i32;
1079 let mycircle = Box::new(mycircle) as Box<Circle>;
1080 let nonsense = mycircle.radius() * mycircle.area();
1083 #### Associated Constants
1086 A trait can define constants like this:
1098 assert_eq!(1, i32::ID);
1102 Any implementor of `Foo` will have to define `ID`. Without the definition:
1116 error: not all trait items implemented, missing: `ID` [E0046]
1121 A default value can be implemented as well:
1136 assert_eq!(1, i32::ID);
1137 assert_eq!(5, i64::ID);
1141 As you can see, when implementing `Foo`, you can leave it unimplemented, as
1142 with `i32`. It will then use the default value. But, as in `i64`, we can also
1143 add our own definition.
1145 Associated constants don’t have to be associated with a trait. An `impl` block
1146 for a `struct` or an `enum` works fine too:
1158 An _implementation_ is an item that implements a [trait](#traits) for a
1161 Implementations are defined with the keyword `impl`.
1164 # #[derive(Copy, Clone)]
1165 # struct Point {x: f64, y: f64};
1166 # type Surface = i32;
1167 # struct BoundingBox {x: f64, y: f64, width: f64, height: f64};
1168 # trait Shape { fn draw(&self, Surface); fn bounding_box(&self) -> BoundingBox; }
1169 # fn do_draw_circle(s: Surface, c: Circle) { }
1175 impl Copy for Circle {}
1177 impl Clone for Circle {
1178 fn clone(&self) -> Circle { *self }
1181 impl Shape for Circle {
1182 fn draw(&self, s: Surface) { do_draw_circle(s, *self); }
1183 fn bounding_box(&self) -> BoundingBox {
1184 let r = self.radius;
1186 x: self.center.x - r,
1187 y: self.center.y - r,
1195 It is possible to define an implementation without referring to a trait. The
1196 methods in such an implementation can only be used as direct calls on the values
1197 of the type that the implementation targets. In such an implementation, the
1198 trait type and `for` after `impl` are omitted. Such implementations are limited
1199 to nominal types (enums, structs, trait objects), and the implementation must
1200 appear in the same crate as the `self` type:
1203 struct Point {x: i32, y: i32}
1207 println!("Point is at ({}, {})", self.x, self.y);
1211 let my_point = Point {x: 10, y:11};
1215 When a trait _is_ specified in an `impl`, all methods declared as part of the
1216 trait must be implemented, with matching types and type parameter counts.
1218 An implementation can take type parameters, which can be different from the
1219 type parameters taken by the trait it implements. Implementation parameters
1220 are written after the `impl` keyword.
1223 # trait Seq<T> { fn dummy(&self, _: T) { } }
1224 impl<T> Seq<T> for Vec<T> {
1227 impl Seq<bool> for u32 {
1228 /* Treat the integer as a sequence of bits */
1234 External blocks form the basis for Rust's foreign function interface.
1235 Declarations in an external block describe symbols in external, non-Rust
1238 Functions within external blocks are declared in the same way as other Rust
1239 functions, with the exception that they may not have a body and are instead
1240 terminated by a semicolon.
1242 Functions within external blocks may be called by Rust code, just like
1243 functions defined in Rust. The Rust compiler automatically translates between
1244 the Rust ABI and the foreign ABI.
1246 Functions within external blocks may be variadic by specifying `...` after one
1247 or more named arguments in the argument list:
1251 fn foo(x: i32, ...);
1255 A number of [attributes] control the behavior of external blocks.
1257 [attributes]: attributes.html#ffi-attributes
1259 By default external blocks assume that the library they are calling uses the
1260 standard C ABI on the specific platform. Other ABIs may be specified using an
1261 `abi` string, as shown here:
1264 // Interface to the Windows API
1265 extern "stdcall" { }
1268 There are three ABI strings which are cross-platform, and which all compilers
1269 are guaranteed to support:
1271 * `extern "Rust"` -- The default ABI when you write a normal `fn foo()` in any
1273 * `extern "C"` -- This is the same as `extern fn foo()`; whatever the default
1274 your C compiler supports.
1275 * `extern "system"` -- Usually the same as `extern "C"`, except on Win32, in
1276 which case it's `"stdcall"`, or what you should use to link to the Windows API
1279 There are also some platform-specific ABI strings:
1281 * `extern "cdecl"` -- The default for x86\_32 C code.
1282 * `extern "stdcall"` -- The default for the Win32 API on x86\_32.
1283 * `extern "win64"` -- The default for C code on x86\_64 Windows.
1284 * `extern "sysv64"` -- The default for C code on non-Windows x86\_64.
1285 * `extern "aapcs"` -- The default for ARM.
1286 * `extern "fastcall"` -- The `fastcall` ABI -- corresponds to MSVC's
1287 `__fastcall` and GCC and clang's `__attribute__((fastcall))`
1288 * `extern "vectorcall"` -- The `vectorcall` ABI -- corresponds to MSVC's
1289 `__vectorcall` and clang's `__attribute__((vectorcall))`
1291 Finally, there are some rustc-specific ABI strings:
1293 * `extern "rust-intrinsic"` -- The ABI of rustc intrinsics.
1294 * `extern "rust-call"` -- The ABI of the Fn::call trait functions.
1295 * `extern "platform-intrinsic"` -- Specific platform intrinsics -- like, for
1296 example, `sqrt` -- have this ABI. You should never have to deal with it.
1298 The `link` attribute allows the name of the library to be specified. When
1299 specified the compiler will attempt to link against the native library of the
1303 #[link(name = "crypto")]
1307 The type of a function declared in an extern block is `extern "abi" fn(A1, ...,
1308 An) -> R`, where `A1...An` are the declared types of its arguments and `R` is
1309 the declared return type.
1311 It is valid to add the `link` attribute on an empty extern block. You can use
1312 this to satisfy the linking requirements of extern blocks elsewhere in your code
1313 (including upstream crates) instead of adding the attribute to each extern block.