]> git.proxmox.com Git - rustc.git/blob - src/doc/reference/src/items.md
cb97b44072b770fef960bfcceb334cb7e51b3bad
[rustc.git] / src / doc / reference / src / items.md
1 # Items
2
3 An _item_ is a component of a crate. Items are organized within a crate by a
4 nested set of [modules]. 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.
7
8 [modules]: #modules
9 [paths]: paths.html
10
11 Items are entirely determined at compile-time, generally remain fixed during
12 execution, and may reside in read-only memory.
13
14 There 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](#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)
29
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.
39
40 ## Type Parameters
41
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.
53
54 [path]: paths.html
55
56 ## Modules
57
58 A module is a container for zero or more [items].
59
60 [items]: items.html
61
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.
65
66 An example of a module:
67
68 ```rust
69 mod math {
70 type Complex = (f64, f64);
71 fn sin(f: f64) -> f64 {
72 /* ... */
73 # panic!();
74 }
75 fn cos(f: f64) -> f64 {
76 /* ... */
77 # panic!();
78 }
79 fn tan(f: f64) -> f64 {
80 /* ... */
81 # panic!();
82 }
83 }
84 ```
85
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.
90
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.
95
96 ```rust,ignore
97 // Load the `vec` module from `vec.rs`
98 mod vec;
99
100 mod thread {
101 // Load the `local_data` module from `thread/local_data.rs`
102 // or `thread/local_data/mod.rs`.
103 mod local_data;
104 }
105 ```
106
107 The directories and files used for loading external file modules can be
108 influenced with the `path` attribute.
109
110 ```rust,ignore
111 #[path = "thread_files"]
112 mod thread {
113 // Load the `local_data` module from `thread_files/tls.rs`
114 #[path = "tls.rs"]
115 mod local_data;
116 }
117 ```
118
119 ### Extern crate declarations
120
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`.
124
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`.
132
133 Three examples of `extern crate` declarations:
134
135 ```rust,ignore
136 extern crate pcre;
137
138 extern crate std; // equivalent to: extern crate std as std;
139
140 extern crate std as ruststd; // linking to 'std' under another name
141 ```
142
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
146 details).
147
148 Here is an example:
149
150 ```rust,ignore
151 // Importing the Cargo package hello-world
152 extern crate hello_world; // hyphen replaced with an underscore
153 ```
154
155 [RFC 940]: https://github.com/rust-lang/rfcs/blob/master/text/0940-hyphens-considered-harmful.md
156
157 ### Use declarations
158
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.
163
164 [path]: paths.html
165 [modules]: #modules
166 [blocks]: ../grammar.html#block-expressions
167
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.
171
172 Use declarations support a number of convenient shortcuts:
173
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
181 ab, c as abc}`.
182 * Binding all paths matching a given prefix, using the asterisk wildcard syntax
183 `use a::b::*;`
184
185 An example of `use` declarations:
186
187 ```rust
188 use std::option::Option::{Some, None};
189 use std::collections::hash_map::{self, HashMap};
190
191 fn foo<T>(_: T){}
192 fn bar(map1: HashMap<String, usize>, map2: hash_map::HashMap<String, usize>){}
193
194 fn main() {
195 // Equivalent to 'foo(vec![std::option::Option::Some(1.0f64),
196 // std::option::Option::None]);'
197 foo(vec![Some(1.0f64), None]);
198
199 // Both `hash_map` and `HashMap` are in scope.
200 let map1 = HashMap::new();
201 let map2 = hash_map::HashMap::new();
202 bar(map1, map2);
203 }
204 ```
205
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.
213
214 An example of re-exporting:
215
216 ```rust
217 # fn main() { }
218 mod quux {
219 pub use quux::foo::{bar, baz};
220
221 pub mod foo {
222 pub fn bar() { }
223 pub fn baz() { }
224 }
225 }
226 ```
227
228 In this example, the module `quux` re-exports two public names defined in
229 `foo`.
230
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`
239 declarations.
240
241 An example of what will and will not work for `use` items:
242
243 ```rust
244 # #![allow(unused_imports)]
245 use foo::baz::foobaz; // good: foo is at the root of the crate
246
247 mod foo {
248
249 mod example {
250 pub mod iter {}
251 }
252
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
257
258 pub mod bar {
259 pub fn foobar() { }
260 }
261
262 pub mod baz {
263 use super::bar::foobar; // good: super refers to module 'foo'
264 pub fn foobaz() { }
265 }
266 }
267
268 fn main() {}
269 ```
270
271 ## Functions
272
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.
280
281 [statements]: statements.html
282 [expression]: expressions.html
283 [variables]: variables.html
284 [type]: types.html
285
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).
290
291 [function type]: types.html#function-types
292
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.
297
298 An example of a function:
299
300 ```rust
301 fn add(x: i32, y: i32) -> i32 {
302 x + y
303 }
304 ```
305
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.
308
309 ```rust
310 fn first((value, _): (i32, i32)) -> i32 { value }
311 ```
312
313
314 ### Generic functions
315
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.
319
320 ```rust,ignore
321 // foo is generic over A and B
322
323 fn foo<A, B>(x: A, y: B) {
324 ```
325
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:
330
331 ```rust,ignore
332 fn foo<T>(x: T) where T: Debug {
333 ```
334
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:
337
338 ```rust
339 use std::fmt::Debug;
340
341 fn foo<T>(x: &[T]) where T: Debug {
342 // details elided
343 # ()
344 }
345
346 foo(&[1, 2]);
347 ```
348
349 will instantiate type parameter `T` with `i32`.
350
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`.
355
356 [path]: paths.html
357
358 ### Diverging functions
359
360 A special kind of function can be declared with a `!` character where the
361 output type would normally be. For example:
362
363 ```rust
364 fn my_err(s: &str) -> ! {
365 println!("{}", s);
366 panic!();
367 }
368 ```
369
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
374 a type.
375
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
380 typecheck:
381
382 [`return`]: expressions.html#return-expressions
383
384 ```rust
385 # fn my_err(s: &str) -> ! { panic!() }
386
387 fn f(i: i32) -> i32 {
388 if i == 42 {
389 return 42;
390 }
391 else {
392 my_err("Bad number!");
393 }
394 }
395 ```
396
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.
404
405 ### Extern functions
406
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`
412 modifier.
413
414 ```rust
415 // Declares an extern fn, the ABI defaults to "C"
416 extern fn new_i32() -> i32 { 0 }
417
418 // Declares an extern fn with "stdcall" ABI
419 # #[cfg(target_arch = "x86_64")]
420 extern "stdcall" fn new_i32_stdcall() -> i32 { 0 }
421 ```
422
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.
425
426 ```rust
427 # extern fn new_i32() -> i32 { 0 }
428 let fptr: extern "C" fn() -> i32 = new_i32;
429 ```
430
431 Extern functions may be called directly from Rust code as Rust uses large,
432 contiguous stack segments like C.
433
434 ## Type aliases
435
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.
440
441 [type]: types.html
442
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:
445
446 ```rust
447 type Point = (u8, u8);
448 let p: Point = (41, 68);
449 ```
450
451 A type alias to an enum type cannot be used to qualify the constructors:
452
453 ```rust
454 enum E { A }
455 type F = E;
456 let _: F = E::A; // OK
457 // let _: F = F::A; // Doesn't work
458 ```
459
460 ## Structs
461
462 A _struct_ is a nominal [struct type] defined with the
463 keyword `struct`.
464
465 An example of a `struct` item and its use:
466
467 ```rust
468 struct Point {x: i32, y: i32}
469 let p = Point {x: 10, y: 11};
470 let px: i32 = p.x;
471 ```
472
473 A _tuple struct_ is a nominal [tuple type], also defined with
474 the keyword `struct`. For example:
475
476 [struct type]: types.html#struct-types
477 [tuple type]: types.html#tuple-types
478
479 ```rust
480 struct Point(i32, i32);
481 let p = Point(10, 11);
482 let px: i32 = match p { Point(x, _) => x };
483 ```
484
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:
488
489 ```rust
490 struct Cookie;
491 let c = [Cookie, Cookie {}, Cookie, Cookie {}];
492 ```
493
494 is equivalent to
495
496 ```rust
497 struct Cookie {}
498 const Cookie: Cookie = Cookie {};
499 let c = [Cookie, Cookie {}, Cookie, Cookie {}];
500 ```
501
502 The precise memory layout of a struct is not specified. One can specify a
503 particular layout using the [`repr` attribute].
504
505 [`repr` attribute]: attributes.html#ffi-attributes
506
507 ## Enumerations
508
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.
512
513 [enumerated type]: types.html#enumerated-types
514
515 Enumerations are declared with the keyword `enum`.
516
517 An example of an `enum` item and its use:
518
519 ```rust
520 enum Animal {
521 Dog,
522 Cat,
523 }
524
525 let mut a: Animal = Animal::Dog;
526 a = Animal::Cat;
527 ```
528
529 Enumeration constructors can have either named or unnamed fields:
530
531 ```rust
532 enum Animal {
533 Dog (String, f64),
534 Cat { name: String, weight: f64 },
535 }
536
537 let mut a: Animal = Animal::Dog("Cocoa".to_string(), 37.2);
538 a = Animal::Cat { name: "Spotty".to_string(), weight: 2.7 };
539 ```
540
541 In this example, `Cat` is a _struct-like enum variant_,
542 whereas `Dog` is simply called an enum variant.
543
544 Each enum value has a _discriminant_ which is an integer associated to it. You
545 can specify it explicitly:
546
547 ```rust
548 enum Foo {
549 Bar = 123,
550 }
551 ```
552
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.
557
558 [`repr` attribute]: attributes.html#ffi-attributes
559
560 If a discriminant isn't specified, they start at zero, and add one for each
561 variant, in order.
562
563 You can cast an enum to get its discriminant:
564
565 ```rust
566 # enum Foo { Bar = 123 }
567 let x = Foo::Bar as u32; // x is now 123u32
568 ```
569
570 This only works as long as none of the variants have data attached. If
571 it were `Bar(i32)`, this is disallowed.
572
573 ## Unions
574
575 A union declaration uses the same syntax as a struct declaration, except with
576 `union` in place of `struct`.
577
578 ```rust
579 #[repr(C)]
580 union MyUnion {
581 f1: u32,
582 f2: f32,
583 }
584 ```
585
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.
589
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:
592
593 ```rust
594 # union MyUnion { f1: u32, f2: f32 }
595 #
596 let u = MyUnion { f1: 1 };
597 ```
598
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:
601
602 ```rust,ignore
603 let f = u.f1;
604 ```
605
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
609 undefined behavior.
610 However, the active field is not generally known statically, so all reads of
611 union fields have to be placed in `unsafe` blocks.
612
613 ```rust
614 # union MyUnion { f1: u32, f2: f32 }
615 # let u = MyUnion { f1: 1 };
616 #
617 unsafe {
618 let f = u.f1;
619 }
620 ```
621
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
624
625 ```rust
626 # union MyUnion { f1: u32, f2: f32 }
627 # let mut u = MyUnion { f1: 1 };
628 #
629 u.f1 = 2;
630 ```
631
632 Commonly, code using unions will provide safe wrappers around unsafe
633 union field accesses.
634
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.
640
641 ```rust
642 # union MyUnion { f1: u32, f2: f32 }
643 #
644 fn f(u: MyUnion) {
645 unsafe {
646 match u {
647 MyUnion { f1: 10 } => { println!("ten"); }
648 MyUnion { f2 } => { println!("{}", f2); }
649 }
650 }
651 }
652 ```
653
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:
657
658 ```rust
659 #[repr(u32)]
660 enum Tag { I, F }
661
662 #[repr(C)]
663 union U {
664 i: i32,
665 f: f32,
666 }
667
668 #[repr(C)]
669 struct Value {
670 tag: Tag,
671 u: U,
672 }
673
674 fn is_zero(v: Value) -> bool {
675 unsafe {
676 match v {
677 Value { tag: I, u: U { i: 0 } } => true,
678 Value { tag: F, u: U { f: 0.0 } } => true,
679 _ => false,
680 }
681 }
682 }
683 ```
684
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.
690
691 ```rust,ignore
692 // ERROR: cannot borrow `u` (via `u.f2`) as mutable more than once at a time
693 fn test() {
694 let mut u = MyUnion { f1: 1 };
695 unsafe {
696 let b1 = &mut u.f1;
697 ---- first mutable borrow occurs here (via `u.f1`)
698 let b2 = &mut u.f2;
699 ^^^^ second mutable borrow occurs here (via `u.f2`)
700 *b1 = 5;
701 }
702 - first borrow ends here
703 assert_eq!(unsafe { u.f1 }, 5);
704 }
705 ```
706
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).
713
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).
716
717 ## Constant items
718
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.
724
725 [constant value]: expressions.html#constant-expressions
726
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.
733
734 [static lifetime elision]: #static-lifetime-elision
735
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.
739
740 ```rust
741 const BIT1: u32 = 1 << 0;
742 const BIT2: u32 = 1 << 1;
743
744 const BITS: [u32; 2] = [BIT1, BIT2];
745 const STRING: &'static str = "bitstring";
746
747 struct BitsNStrings<'a> {
748 mybits: [u32; 2],
749 mystring: &'a str,
750 }
751
752 const BITS_N_STRINGS: BitsNStrings<'static> = BitsNStrings {
753 mybits: BITS,
754 mystring: STRING,
755 };
756 ```
757
758 ## Static items
759
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
765 interior mutability.
766
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
769 statics:
770
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.
775
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.
778
779 ### Mutable statics
780
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.
788
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).
791
792 ```rust
793 # fn atomic_add(_: &mut u32, _: u32) -> u32 { 2 }
794
795 static mut LEVELS: u32 = 0;
796
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 {
800 let ret = LEVELS;
801 LEVELS += 1;
802 return ret;
803 }
804
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);
810 }
811 ```
812
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`.
815
816 #### `'static` lifetime elision
817
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:
822
823 ```rust
824 const BIT1: u32 = 1 << 0;
825 const BIT2: u32 = 1 << 1;
826
827 const BITS: [u32; 2] = [BIT1, BIT2];
828 const STRING: &str = "bitstring";
829
830 struct BitsNStrings<'a> {
831 mybits: [u32; 2],
832 mystring: &'a str,
833 }
834
835 const BITS_N_STRINGS: BitsNStrings = BitsNStrings {
836 mybits: BITS,
837 mystring: STRING,
838 };
839 ```
840
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:
846
847 [elision-nomicon]: ../nomicon/lifetime-elision.html
848
849 ```rust,ignore
850 // Resolved as `fn<'a>(&'a str) -> &'a str`.
851 const RESOLVED_SINGLE: fn(&str) -> &str = ..
852
853 // Resolved as `Fn<'a, 'b, 'c>(&'a Foo, &'b Bar, &'c Baz) -> usize`.
854 const RESOLVED_MULTIPLE: Fn(&Foo, &Bar, &Baz) -> usize = ..
855
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 = ..
860 ```
861
862 ### Traits
863
864 A _trait_ describes an abstract interface that types can
865 implement. This interface consists of associated items, which come in
866 three varieties:
867
868 - functions
869 - [constants](#associated-constants)
870 - types
871
872 Associated functions whose first parameter is named `self` are called
873 methods and may be invoked using `.` notation (e.g., `x.foo()`).
874
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.
879
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].
884
885 Traits are implemented for specific types through separate
886 [implementations].
887
888 Consider the following trait:
889
890 ```rust
891 # type Surface = i32;
892 # type BoundingBox = i32;
893 trait Shape {
894 fn draw(&self, Surface);
895 fn bounding_box(&self) -> BoundingBox;
896 }
897 ```
898
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()`
902 [syntax].
903
904 [trait object]: types.html#trait-objects
905 [implementations]: #implementations
906 [syntax]: expressions.html#method-call-expressions
907
908 Traits can include default implementations of methods, as in:
909
910 ```rust
911 trait Foo {
912 fn bar(&self);
913 fn baz(&self) { println!("We called baz."); }
914 }
915 ```
916
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.
920
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).
924
925 ```rust
926 trait Seq<T> {
927 fn len(&self) -> u32;
928 fn elt_at(&self, n: u32) -> T;
929 fn iter<F>(&self, F) where F: Fn(T);
930 }
931 ```
932
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:
936
937 ```rust
938 trait Container {
939 type E;
940 fn empty() -> Self;
941 fn insert(&mut self, Self::E);
942 }
943 ```
944
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`:
948
949 ```rust
950 # trait Container {
951 # type E;
952 # fn empty() -> Self;
953 # fn insert(&mut self, Self::E);
954 # }
955 impl<T> Container for Vec<T> {
956 type E = T;
957 fn empty() -> Vec<T> { Vec::new() }
958 fn insert(&mut self, x: T) { self.push(x); }
959 }
960 ```
961
962 Generic functions may use traits as _bounds_ on their type parameters. This
963 will have two effects:
964
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.
968
969 For example:
970
971 ```rust
972 # type Surface = i32;
973 # trait Shape { fn draw(&self, Surface); }
974 fn draw_twice<T: Shape>(surface: Surface, sh: T) {
975 sh.draw(surface);
976 sh.draw(surface);
977 }
978 ```
979
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
986 coercion:
987
988 [trait object]: types.html#trait-objects
989 [explicit]: expressions.html#type-cast-expressions
990
991 ```rust
992 trait Shape { }
993 impl Shape for i32 { }
994 let mycircle = 0i32;
995 let myshape: Box<Shape> = Box::new(mycircle) as Box<Shape>;
996 ```
997
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.
1003
1004 [methods called]: expressions.html#method-call-expressions
1005
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:
1011
1012 ```rust
1013 trait Num {
1014 fn from_i32(n: i32) -> Self;
1015 }
1016 impl Num for f64 {
1017 fn from_i32(n: i32) -> f64 { n as f64 }
1018 }
1019 let x: f64 = Num::from_i32(42);
1020 ```
1021
1022 Traits may inherit from other traits. Consider the following example:
1023
1024 ```rust
1025 trait Shape { fn area(&self) -> f64; }
1026 trait Circle : Shape { fn radius(&self) -> f64; }
1027 ```
1028
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`:
1035
1036 ```rust
1037 struct Foo;
1038
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 {
1043 0.0
1044 }
1045 }
1046 impl Circle for Foo {
1047 fn radius(&self) -> f64 {
1048 println!("calling area: {}", self.area());
1049
1050 0.0
1051 }
1052 }
1053
1054 let c = Foo;
1055 c.radius();
1056 ```
1057
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`:
1061
1062 ```rust
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()
1068 }
1069 ```
1070
1071 Likewise, supertrait methods may also be called on trait objects.
1072
1073 ```rust,ignore
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();
1081 ```
1082
1083 #### Associated Constants
1084
1085
1086 A trait can define constants like this:
1087
1088 ```rust
1089 trait Foo {
1090 const ID: i32;
1091 }
1092
1093 impl Foo for i32 {
1094 const ID: i32 = 1;
1095 }
1096
1097 fn main() {
1098 assert_eq!(1, i32::ID);
1099 }
1100 ```
1101
1102 Any implementor of `Foo` will have to define `ID`. Without the definition:
1103
1104 ```rust,ignore
1105 trait Foo {
1106 const ID: i32;
1107 }
1108
1109 impl Foo for i32 {
1110 }
1111 ```
1112
1113 gives
1114
1115 ```text
1116 error: not all trait items implemented, missing: `ID` [E0046]
1117 impl Foo for i32 {
1118 }
1119 ```
1120
1121 A default value can be implemented as well:
1122
1123 ```rust
1124 trait Foo {
1125 const ID: i32 = 1;
1126 }
1127
1128 impl Foo for i32 {
1129 }
1130
1131 impl Foo for i64 {
1132 const ID: i32 = 5;
1133 }
1134
1135 fn main() {
1136 assert_eq!(1, i32::ID);
1137 assert_eq!(5, i64::ID);
1138 }
1139 ```
1140
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.
1144
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:
1147
1148 ```rust
1149 struct Foo;
1150
1151 impl Foo {
1152 const FOO: u32 = 3;
1153 }
1154 ```
1155
1156 ### Implementations
1157
1158 An _implementation_ is an item that implements a [trait](#traits) for a
1159 specific type.
1160
1161 Implementations are defined with the keyword `impl`.
1162
1163 ```rust
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) { }
1170 struct Circle {
1171 radius: f64,
1172 center: Point,
1173 }
1174
1175 impl Copy for Circle {}
1176
1177 impl Clone for Circle {
1178 fn clone(&self) -> Circle { *self }
1179 }
1180
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;
1185 BoundingBox {
1186 x: self.center.x - r,
1187 y: self.center.y - r,
1188 width: 2.0 * r,
1189 height: 2.0 * r,
1190 }
1191 }
1192 }
1193 ```
1194
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:
1201
1202 ```rust
1203 struct Point {x: i32, y: i32}
1204
1205 impl Point {
1206 fn log(&self) {
1207 println!("Point is at ({}, {})", self.x, self.y);
1208 }
1209 }
1210
1211 let my_point = Point {x: 10, y:11};
1212 my_point.log();
1213 ```
1214
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.
1217
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.
1221
1222 ```rust
1223 # trait Seq<T> { fn dummy(&self, _: T) { } }
1224 impl<T> Seq<T> for Vec<T> {
1225 /* ... */
1226 }
1227 impl Seq<bool> for u32 {
1228 /* Treat the integer as a sequence of bits */
1229 }
1230 ```
1231
1232 ### External blocks
1233
1234 External blocks form the basis for Rust's foreign function interface.
1235 Declarations in an external block describe symbols in external, non-Rust
1236 libraries.
1237
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.
1241
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.
1245
1246 Functions within external blocks may be variadic by specifying `...` after one
1247 or more named arguments in the argument list:
1248
1249 ```rust,ignore
1250 extern {
1251 fn foo(x: i32, ...);
1252 }
1253 ```
1254
1255 A number of [attributes] control the behavior of external blocks.
1256
1257 [attributes]: attributes.html#ffi-attributes
1258
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:
1262
1263 ```rust,ignore
1264 // Interface to the Windows API
1265 extern "stdcall" { }
1266 ```
1267
1268 There are three ABI strings which are cross-platform, and which all compilers
1269 are guaranteed to support:
1270
1271 * `extern "Rust"` -- The default ABI when you write a normal `fn foo()` in any
1272 Rust code.
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
1277 itself
1278
1279 There are also some platform-specific ABI strings:
1280
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))`
1290
1291 Finally, there are some rustc-specific ABI strings:
1292
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.
1297
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
1300 specified name.
1301
1302 ```rust,ignore
1303 #[link(name = "crypto")]
1304 extern { }
1305 ```
1306
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.
1310
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.