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.
8 Items are entirely determined at compile-time, generally remain fixed during
9 execution, and may reside in read-only memory.
11 There are several kinds of item:
13 * [`extern crate` declarations](#extern-crate-declarations)
14 * [`use` declarations](#use-declarations)
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)
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.
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.
52 A module is a container for zero or more [items](#items).
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.
58 An example of a module:
62 type Complex = (f64, f64);
63 fn sin(f: f64) -> f64 {
67 fn cos(f: f64) -> f64 {
71 fn tan(f: f64) -> f64 {
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.
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.
89 // Load the `vec` module from `vec.rs`
93 // Load the `local_data` module from `thread/local_data.rs`
94 // or `thread/local_data/mod.rs`.
99 The directories and files used for loading external file modules can be
100 influenced with the `path` attribute.
103 #[path = "thread_files"]
105 // Load the `local_data` module from `thread_files/tls.rs`
111 ### Extern crate declarations
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`.
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`.
125 Three examples of `extern crate` declarations:
130 extern crate std; // equivalent to: extern crate std as std;
132 extern crate std as ruststd; // linking to 'std' under another name
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
143 // Importing the Cargo package hello-world
144 extern crate hello_world; // hyphen replaced with an underscore
147 [RFC 940]: https://github.com/rust-lang/rfcs/blob/master/text/0940-hyphens-considered-harmful.md
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.
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.
160 Use declarations support a number of convenient shortcuts:
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
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};`
171 An example of `use` declarations:
174 use std::option::Option::{Some, None};
175 use std::collections::hash_map::{self, HashMap};
178 fn bar(map1: HashMap<String, usize>, map2: hash_map::HashMap<String, usize>){}
181 // Equivalent to 'foo(vec![std::option::Option::Some(1.0f64),
182 // std::option::Option::None]);'
183 foo(vec![Some(1.0f64), None]);
185 // Both `hash_map` and `HashMap` are in scope.
186 let map1 = HashMap::new();
187 let map2 = hash_map::HashMap::new();
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.
200 An example of re-exporting:
205 pub use quux::foo::{bar, baz};
214 In this example, the module `quux` re-exports two public names defined in
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`
227 An example of what will and will not work for `use` items:
230 # #![allow(unused_imports)]
231 use foo::baz::foobaz; // good: foo is at the root of the crate
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
249 use super::bar::foobar; // good: super refers to module 'foo'
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.
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).
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.
277 An example of a function:
280 fn add(x: i32, y: i32) -> i32 {
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.
289 fn first((value, _): (i32, i32)) -> i32 { value }
293 ### Generic functions
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.
300 // foo is generic over A and B
302 fn foo<A, B>(x: A, y: B) {
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:
311 fn foo<T>(x: T) where T: Debug {
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:
320 fn foo<T>(x: &[T]) where T: Debug {
328 will instantiate type parameter `T` with `i32`.
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`.
335 ### Diverging functions
337 A special kind of function can be declared with a `!` character where the
338 output type would normally be. For example:
341 fn my_err(s: &str) -> ! {
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.
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
359 # fn my_err(s: &str) -> ! { panic!() }
361 fn f(i: i32) -> i32 {
366 my_err("Bad number!");
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.
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`
389 // Declares an extern fn, the ABI defaults to "C"
390 extern fn new_i32() -> i32 { 0 }
392 // Declares an extern fn with "stdcall" ABI
393 extern "stdcall" fn new_i32_stdcall() -> i32 { 0 }
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.
400 # extern fn new_i32() -> i32 { 0 }
401 let fptr: extern "C" fn() -> i32 = new_i32;
404 Extern functions may be called directly from Rust code as Rust uses large,
405 contiguous stack segments like C.
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.
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:
418 type Point = (u8, u8);
419 let p: Point = (41, 68);
422 Currently a type alias to an enum type cannot be used to qualify the
428 let _: F = E::A; // OK
429 // let _: F = F::A; // Doesn't work
434 A _struct_ is a nominal [struct type](#struct-types) defined with the
437 An example of a `struct` item and its use:
440 struct Point {x: i32, y: i32}
441 let p = Point {x: 10, y: 11};
445 A _tuple struct_ is a nominal [tuple type](#tuple-types), also defined with
446 the keyword `struct`. For example:
449 struct Point(i32, i32);
450 let p = Point(10, 11);
451 let px: i32 = match p { Point(x, _) => x };
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:
460 let c = [Cookie, Cookie {}, Cookie, Cookie {}];
467 const Cookie: Cookie = Cookie {};
468 let c = [Cookie, Cookie {}, Cookie, Cookie {}];
471 The precise memory layout of a struct is not specified. One can specify a
472 particular layout using the [`repr` attribute](#ffi-attributes).
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.
480 Enumerations are declared with the keyword `enum`.
482 An example of an `enum` item and its use:
490 let mut a: Animal = Animal::Dog;
494 Enumeration constructors can have either named or unnamed fields:
499 Cat { name: String, weight: f64 },
502 let mut a: Animal = Animal::Dog("Cocoa".to_string(), 37.2);
503 a = Animal::Cat { name: "Spotty".to_string(), weight: 2.7 };
506 In this example, `Cat` is a _struct-like enum variant_,
507 whereas `Dog` is simply called an enum variant.
509 Each enum value has a _discriminant_ which is an integer associated to it. You
510 can specify it explicitly:
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.
523 If a discriminant isn't specified, they start at zero, and add one for each
526 You can cast an enum to get its discriminant:
529 # enum Foo { Bar = 123 }
530 let x = Foo::Bar as u32; // x is now 123u32
533 This only works as long as none of the variants have data attached. If
534 it were `Bar(i32)`, this is disallowed.
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.
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.
551 [static lifetime elision]: #static-lifetime-elision
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.
558 const BIT1: u32 = 1 << 0;
559 const BIT2: u32 = 1 << 1;
561 const BITS: [u32; 2] = [BIT1, BIT2];
562 const STRING: &'static str = "bitstring";
564 struct BitsNStrings<'a> {
569 const BITS_N_STRINGS: BitsNStrings<'static> = BitsNStrings {
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
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
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.
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.
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.
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).
610 # fn atomic_add(_: &mut u32, _: u32) -> u32 { 2 }
612 static mut LEVELS: u32 = 0;
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 {
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);
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`.
633 #### `'static` lifetime elision
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:
641 # #![feature(static_in_const)]
642 const BIT1: u32 = 1 << 0;
643 const BIT2: u32 = 1 << 1;
645 const BITS: [u32; 2] = [BIT1, BIT2];
646 const STRING: &str = "bitstring";
648 struct BitsNStrings<'a> {
653 const BITS_N_STRINGS: BitsNStrings = BitsNStrings {
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:
665 [elision-nomicon]: https://doc.rust-lang.org/nomicon/lifetime-elision.html
668 // Resolved as `fn<'a>(&'a str) -> &'a str`.
669 const RESOLVED_SINGLE: fn(&str) -> &str = ..
671 // Resolved as `Fn<'a, 'b, 'c>(&'a Foo, &'b Bar, &'c Baz) -> usize`.
672 const RESOLVED_MULTIPLE: Fn(&Foo, &Bar, &Baz) -> usize = ..
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 = ..
682 A _trait_ describes an abstract interface that types can
683 implement. This interface consists of associated items, which come in
690 Associated functions whose first parameter is named `self` are called
691 methods and may be invoked using `.` notation (e.g., `x.foo()`).
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.
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).
703 Traits are implemented for specific types through separate
704 [implementations](#implementations).
706 Consider the following trait:
709 # type Surface = i32;
710 # type BoundingBox = i32;
712 fn draw(&self, Surface);
713 fn bounding_box(&self) -> BoundingBox;
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).
722 Traits can include default implementations of methods, as in:
727 fn baz(&self) { println!("We called baz."); }
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.
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).
741 fn len(&self) -> u32;
742 fn elt_at(&self, n: u32) -> T;
743 fn iter<F>(&self, F) where F: Fn(T);
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:
755 fn insert(&mut self, Self::E);
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`:
766 # fn empty() -> Self;
767 # fn insert(&mut self, Self::E);
769 impl<T> Container for Vec<T> {
771 fn empty() -> Vec<T> { Vec::new() }
772 fn insert(&mut self, x: T) { self.push(x); }
776 Generic functions may use traits as _bounds_ on their type parameters. This
777 will have two effects:
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.
786 # type Surface = i32;
787 # trait Shape { fn draw(&self, Surface); }
788 fn draw_twice<T: Shape>(surface: Surface, sh: T) {
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
804 impl Shape for i32 { }
806 let myshape: Box<Shape> = Box::new(mycircle) as Box<Shape>;
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.
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
823 fn from_i32(n: i32) -> Self;
826 fn from_i32(n: i32) -> f64 { n as f64 }
828 let x: f64 = Num::from_i32(42);
831 Traits may inherit from other traits. Consider the following example:
834 trait Shape { fn area(&self) -> f64; }
835 trait Circle : Shape { fn radius(&self) -> f64; }
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`:
848 trait Shape { fn area(&self) -> f64; }
849 trait Circle : Shape { fn radius(&self) -> f64; }
851 fn area(&self) -> f64 {
855 impl Circle for Foo {
856 fn radius(&self) -> f64 {
857 println!("calling area: {}", self.area());
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`:
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()
880 Likewise, supertrait methods may also be called on trait objects.
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();
894 An _implementation_ is an item that implements a [trait](#traits) for a
897 Implementations are defined with the keyword `impl`.
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) { }
911 impl Copy for Circle {}
913 impl Clone for Circle {
914 fn clone(&self) -> Circle { *self }
917 impl Shape for Circle {
918 fn draw(&self, s: Surface) { do_draw_circle(s, *self); }
919 fn bounding_box(&self) -> BoundingBox {
922 x: self.center.x - r,
923 y: self.center.y - r,
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:
939 struct Point {x: i32, y: i32}
943 println!("Point is at ({}, {})", self.x, self.y);
947 let my_point = Point {x: 10, y:11};
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.
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.
959 # trait Seq<T> { fn dummy(&self, _: T) { } }
960 impl<T> Seq<T> for Vec<T> {
963 impl Seq<bool> for u32 {
964 /* Treat the integer as a sequence of bits */
970 External blocks form the basis for Rust's foreign function interface.
971 Declarations in an external block describe symbols in external, non-Rust
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.
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.
982 Functions within external blocks may be variadic by specifying `...` after one
983 or more named arguments in the argument list:
991 A number of [attributes](#ffi-attributes) control the behavior of external blocks.
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:
998 // Interface to the Windows API
1002 There are three ABI strings which are cross-platform, and which all compilers
1003 are guaranteed to support:
1005 * `extern "Rust"` -- The default ABI when you write a normal `fn foo()` in any
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
1013 There are also some platform-specific ABI strings:
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))`
1025 Finally, there are some rustc-specific ABI strings:
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.
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
1037 #[link(name = "crypto")]
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.
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.