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