]> git.proxmox.com Git - rustc.git/blob - src/doc/trpl/crates-and-modules.md
Imported Upstream version 1.3.0+dfsg1
[rustc.git] / src / doc / trpl / crates-and-modules.md
1 % Crates and Modules
2
3 When a project starts getting large, it’s considered good software
4 engineering practice to split it up into a bunch of smaller pieces, and then
5 fit them together. It’s also important to have a well-defined interface, so
6 that some of your functionality is private, and some is public. To facilitate
7 these kinds of things, Rust has a module system.
8
9 # Basic terminology: Crates and Modules
10
11 Rust has two distinct terms that relate to the module system: ‘crate’ and
12 ‘module’. A crate is synonymous with a ‘library’ or ‘package’ in other
13 languages. Hence “Cargo” as the name of Rust’s package management tool: you
14 ship your crates to others with Cargo. Crates can produce an executable or a
15 library, depending on the project.
16
17 Each crate has an implicit *root module* that contains the code for that crate.
18 You can then define a tree of sub-modules under that root module. Modules allow
19 you to partition your code within the crate itself.
20
21 As an example, let’s make a *phrases* crate, which will give us various phrases
22 in different languages. To keep things simple, we’ll stick to ‘greetings’ and
23 ‘farewells’ as two kinds of phrases, and use English and Japanese (日本語) as
24 two languages for those phrases to be in. We’ll use this module layout:
25
26 ```text
27 +-----------+
28 +---| greetings |
29 | +-----------+
30 +---------+ |
31 +---| english |---+
32 | +---------+ | +-----------+
33 | +---| farewells |
34 +---------+ | +-----------+
35 | phrases |---+
36 +---------+ | +-----------+
37 | +---| greetings |
38 | +----------+ | +-----------+
39 +---| japanese |--+
40 +----------+ |
41 | +-----------+
42 +---| farewells |
43 +-----------+
44 ```
45
46 In this example, `phrases` is the name of our crate. All of the rest are
47 modules. You can see that they form a tree, branching out from the crate
48 *root*, which is the root of the tree: `phrases` itself.
49
50 Now that we have a plan, let’s define these modules in code. To start,
51 generate a new crate with Cargo:
52
53 ```bash
54 $ cargo new phrases
55 $ cd phrases
56 ```
57
58 If you remember, this generates a simple project for us:
59
60 ```bash
61 $ tree .
62 .
63 ├── Cargo.toml
64 └── src
65 └── lib.rs
66
67 1 directory, 2 files
68 ```
69
70 `src/lib.rs` is our crate root, corresponding to the `phrases` in our diagram
71 above.
72
73 # Defining Modules
74
75 To define each of our modules, we use the `mod` keyword. Let’s make our
76 `src/lib.rs` look like this:
77
78 ```rust
79 mod english {
80 mod greetings {
81 }
82
83 mod farewells {
84 }
85 }
86
87 mod japanese {
88 mod greetings {
89 }
90
91 mod farewells {
92 }
93 }
94 ```
95
96 After the `mod` keyword, you give the name of the module. Module names follow
97 the conventions for other Rust identifiers: `lower_snake_case`. The contents of
98 each module are within curly braces (`{}`).
99
100 Within a given `mod`, you can declare sub-`mod`s. We can refer to sub-modules
101 with double-colon (`::`) notation: our four nested modules are
102 `english::greetings`, `english::farewells`, `japanese::greetings`, and
103 `japanese::farewells`. Because these sub-modules are namespaced under their
104 parent module, the names don’t conflict: `english::greetings` and
105 `japanese::greetings` are distinct, even though their names are both
106 `greetings`.
107
108 Because this crate does not have a `main()` function, and is called `lib.rs`,
109 Cargo will build this crate as a library:
110
111 ```bash
112 $ cargo build
113 Compiling phrases v0.0.1 (file:///home/you/projects/phrases)
114 $ ls target/debug
115 build deps examples libphrases-a7448e02a0468eaa.rlib native
116 ```
117
118 `libphrase-hash.rlib` is the compiled crate. Before we see how to use this
119 crate from another crate, let’s break it up into multiple files.
120
121 # Multiple file crates
122
123 If each crate were just one file, these files would get very large. It’s often
124 easier to split up crates into multiple files, and Rust supports this in two
125 ways.
126
127 Instead of declaring a module like this:
128
129 ```rust,ignore
130 mod english {
131 // contents of our module go here
132 }
133 ```
134
135 We can instead declare our module like this:
136
137 ```rust,ignore
138 mod english;
139 ```
140
141 If we do that, Rust will expect to find either a `english.rs` file, or a
142 `english/mod.rs` file with the contents of our module.
143
144 Note that in these files, you don’t need to re-declare the module: that’s
145 already been done with the initial `mod` declaration.
146
147 Using these two techniques, we can break up our crate into two directories and
148 seven files:
149
150 ```bash
151 $ tree .
152 .
153 ├── Cargo.lock
154 ├── Cargo.toml
155 ├── src
156 │   ├── english
157 │   │   ├── farewells.rs
158 │   │   ├── greetings.rs
159 │   │   └── mod.rs
160 │   ├── japanese
161 │   │   ├── farewells.rs
162 │   │   ├── greetings.rs
163 │   │   └── mod.rs
164 │   └── lib.rs
165 └── target
166 └── debug
167 ├── build
168 ├── deps
169 ├── examples
170 ├── libphrases-a7448e02a0468eaa.rlib
171 └── native
172 ```
173
174 `src/lib.rs` is our crate root, and looks like this:
175
176 ```rust,ignore
177 mod english;
178 mod japanese;
179 ```
180
181 These two declarations tell Rust to look for either `src/english.rs` and
182 `src/japanese.rs`, or `src/english/mod.rs` and `src/japanese/mod.rs`, depending
183 on our preference. In this case, because our modules have sub-modules, we’ve
184 chosen the second. Both `src/english/mod.rs` and `src/japanese/mod.rs` look
185 like this:
186
187 ```rust,ignore
188 mod greetings;
189 mod farewells;
190 ```
191
192 Again, these declarations tell Rust to look for either
193 `src/english/greetings.rs` and `src/japanese/greetings.rs` or
194 `src/english/farewells/mod.rs` and `src/japanese/farewells/mod.rs`. Because
195 these sub-modules don’t have their own sub-modules, we’ve chosen to make them
196 `src/english/greetings.rs` and `src/japanese/farewells.rs`. Whew!
197
198 The contents of `src/english/greetings.rs` and `src/japanese/farewells.rs` are
199 both empty at the moment. Let’s add some functions.
200
201 Put this in `src/english/greetings.rs`:
202
203 ```rust
204 fn hello() -> String {
205 "Hello!".to_string()
206 }
207 ```
208
209 Put this in `src/english/farewells.rs`:
210
211 ```rust
212 fn goodbye() -> String {
213 "Goodbye.".to_string()
214 }
215 ```
216
217 Put this in `src/japanese/greetings.rs`:
218
219 ```rust
220 fn hello() -> String {
221 "こんにちは".to_string()
222 }
223 ```
224
225 Of course, you can copy and paste this from this web page, or just type
226 something else. It’s not important that you actually put ‘konnichiwa’ to learn
227 about the module system.
228
229 Put this in `src/japanese/farewells.rs`:
230
231 ```rust
232 fn goodbye() -> String {
233 "さようなら".to_string()
234 }
235 ```
236
237 (This is ‘Sayōnara’, if you’re curious.)
238
239 Now that we have some functionality in our crate, let’s try to use it from
240 another crate.
241
242 # Importing External Crates
243
244 We have a library crate. Let’s make an executable crate that imports and uses
245 our library.
246
247 Make a `src/main.rs` and put this in it (it won’t quite compile yet):
248
249 ```rust,ignore
250 extern crate phrases;
251
252 fn main() {
253 println!("Hello in English: {}", phrases::english::greetings::hello());
254 println!("Goodbye in English: {}", phrases::english::farewells::goodbye());
255
256 println!("Hello in Japanese: {}", phrases::japanese::greetings::hello());
257 println!("Goodbye in Japanese: {}", phrases::japanese::farewells::goodbye());
258 }
259 ```
260
261 The `extern crate` declaration tells Rust that we need to compile and link to
262 the `phrases` crate. We can then use `phrases`’ modules in this one. As we
263 mentioned earlier, you can use double colons to refer to sub-modules and the
264 functions inside of them.
265
266 Also, Cargo assumes that `src/main.rs` is the crate root of a binary crate,
267 rather than a library crate. Our package now has two crates: `src/lib.rs` and
268 `src/main.rs`. This pattern is quite common for executable crates: most
269 functionality is in a library crate, and the executable crate uses that
270 library. This way, other programs can also use the library crate, and it’s also
271 a nice separation of concerns.
272
273 This doesn’t quite work yet, though. We get four errors that look similar to
274 this:
275
276 ```bash
277 $ cargo build
278 Compiling phrases v0.0.1 (file:///home/you/projects/phrases)
279 src/main.rs:4:38: 4:72 error: function `hello` is private
280 src/main.rs:4 println!("Hello in English: {}", phrases::english::greetings::hello());
281 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
282 note: in expansion of format_args!
283 <std macros>:2:25: 2:58 note: expansion site
284 <std macros>:1:1: 2:62 note: in expansion of print!
285 <std macros>:3:1: 3:54 note: expansion site
286 <std macros>:1:1: 3:58 note: in expansion of println!
287 phrases/src/main.rs:4:5: 4:76 note: expansion site
288 ```
289
290 By default, everything is private in Rust. Let’s talk about this in some more
291 depth.
292
293 # Exporting a Public Interface
294
295 Rust allows you to precisely control which aspects of your interface are
296 public, and so private is the default. To make things public, you use the `pub`
297 keyword. Let’s focus on the `english` module first, so let’s reduce our `src/main.rs`
298 to just this:
299
300 ```rust,ignore
301 extern crate phrases;
302
303 fn main() {
304 println!("Hello in English: {}", phrases::english::greetings::hello());
305 println!("Goodbye in English: {}", phrases::english::farewells::goodbye());
306 }
307 ```
308
309 In our `src/lib.rs`, let’s add `pub` to the `english` module declaration:
310
311 ```rust,ignore
312 pub mod english;
313 mod japanese;
314 ```
315
316 And in our `src/english/mod.rs`, let’s make both `pub`:
317
318 ```rust,ignore
319 pub mod greetings;
320 pub mod farewells;
321 ```
322
323 In our `src/english/greetings.rs`, let’s add `pub` to our `fn` declaration:
324
325 ```rust,ignore
326 pub fn hello() -> String {
327 "Hello!".to_string()
328 }
329 ```
330
331 And also in `src/english/farewells.rs`:
332
333 ```rust,ignore
334 pub fn goodbye() -> String {
335 "Goodbye.".to_string()
336 }
337 ```
338
339 Now, our crate compiles, albeit with warnings about not using the `japanese`
340 functions:
341
342 ```bash
343 $ cargo run
344 Compiling phrases v0.0.1 (file:///home/you/projects/phrases)
345 src/japanese/greetings.rs:1:1: 3:2 warning: function is never used: `hello`, #[warn(dead_code)] on by default
346 src/japanese/greetings.rs:1 fn hello() -> String {
347 src/japanese/greetings.rs:2 "こんにちは".to_string()
348 src/japanese/greetings.rs:3 }
349 src/japanese/farewells.rs:1:1: 3:2 warning: function is never used: `goodbye`, #[warn(dead_code)] on by default
350 src/japanese/farewells.rs:1 fn goodbye() -> String {
351 src/japanese/farewells.rs:2 "さようなら".to_string()
352 src/japanese/farewells.rs:3 }
353 Running `target/debug/phrases`
354 Hello in English: Hello!
355 Goodbye in English: Goodbye.
356 ```
357
358 `pub` also applies to `struct`s and their member fields. In keeping with Rust’s
359 tendency toward safety, simply making a `struct` public won't automatically
360 make its members public: you must mark the fields individually with `pub`.
361
362 Now that our functions are public, we can use them. Great! However, typing out
363 `phrases::english::greetings::hello()` is very long and repetitive. Rust has
364 another keyword for importing names into the current scope, so that you can
365 refer to them with shorter names. Let’s talk about `use`.
366
367 # Importing Modules with `use`
368
369 Rust has a `use` keyword, which allows us to import names into our local scope.
370 Let’s change our `src/main.rs` to look like this:
371
372 ```rust,ignore
373 extern crate phrases;
374
375 use phrases::english::greetings;
376 use phrases::english::farewells;
377
378 fn main() {
379 println!("Hello in English: {}", greetings::hello());
380 println!("Goodbye in English: {}", farewells::goodbye());
381 }
382 ```
383
384 The two `use` lines import each module into the local scope, so we can refer to
385 the functions by a much shorter name. By convention, when importing functions, it’s
386 considered best practice to import the module, rather than the function directly. In
387 other words, you _can_ do this:
388
389 ```rust,ignore
390 extern crate phrases;
391
392 use phrases::english::greetings::hello;
393 use phrases::english::farewells::goodbye;
394
395 fn main() {
396 println!("Hello in English: {}", hello());
397 println!("Goodbye in English: {}", goodbye());
398 }
399 ```
400
401 But it is not idiomatic. This is significantly more likely to introduce a
402 naming conflict. In our short program, it’s not a big deal, but as it grows, it
403 becomes a problem. If we have conflicting names, Rust will give a compilation
404 error. For example, if we made the `japanese` functions public, and tried to do
405 this:
406
407 ```rust,ignore
408 extern crate phrases;
409
410 use phrases::english::greetings::hello;
411 use phrases::japanese::greetings::hello;
412
413 fn main() {
414 println!("Hello in English: {}", hello());
415 println!("Hello in Japanese: {}", hello());
416 }
417 ```
418
419 Rust will give us a compile-time error:
420
421 ```text
422 Compiling phrases v0.0.1 (file:///home/you/projects/phrases)
423 src/main.rs:4:5: 4:40 error: a value named `hello` has already been imported in this module [E0252]
424 src/main.rs:4 use phrases::japanese::greetings::hello;
425 ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
426 error: aborting due to previous error
427 Could not compile `phrases`.
428 ```
429
430 If we’re importing multiple names from the same module, we don’t have to type it out
431 twice. Instead of this:
432
433 ```rust,ignore
434 use phrases::english::greetings;
435 use phrases::english::farewells;
436 ```
437
438 We can use this shortcut:
439
440 ```rust,ignore
441 use phrases::english::{greetings, farewells};
442 ```
443
444 ## Re-exporting with `pub use`
445
446 You don’t just use `use` to shorten identifiers. You can also use it inside of your crate
447 to re-export a function inside another module. This allows you to present an external
448 interface that may not directly map to your internal code organization.
449
450 Let’s look at an example. Modify your `src/main.rs` to read like this:
451
452 ```rust,ignore
453 extern crate phrases;
454
455 use phrases::english::{greetings,farewells};
456 use phrases::japanese;
457
458 fn main() {
459 println!("Hello in English: {}", greetings::hello());
460 println!("Goodbye in English: {}", farewells::goodbye());
461
462 println!("Hello in Japanese: {}", japanese::hello());
463 println!("Goodbye in Japanese: {}", japanese::goodbye());
464 }
465 ```
466
467 Then, modify your `src/lib.rs` to make the `japanese` mod public:
468
469 ```rust,ignore
470 pub mod english;
471 pub mod japanese;
472 ```
473
474 Next, make the two functions public, first in `src/japanese/greetings.rs`:
475
476 ```rust,ignore
477 pub fn hello() -> String {
478 "こんにちは".to_string()
479 }
480 ```
481
482 And then in `src/japanese/farewells.rs`:
483
484 ```rust,ignore
485 pub fn goodbye() -> String {
486 "さようなら".to_string()
487 }
488 ```
489
490 Finally, modify your `src/japanese/mod.rs` to read like this:
491
492 ```rust,ignore
493 pub use self::greetings::hello;
494 pub use self::farewells::goodbye;
495
496 mod greetings;
497 mod farewells;
498 ```
499
500 The `pub use` declaration brings the function into scope at this part of our
501 module hierarchy. Because we’ve `pub use`d this inside of our `japanese`
502 module, we now have a `phrases::japanese::hello()` function and a
503 `phrases::japanese::goodbye()` function, even though the code for them lives in
504 `phrases::japanese::greetings::hello()` and
505 `phrases::japanese::farewells::goodbye()`. Our internal organization doesn’t
506 define our external interface.
507
508 Here we have a `pub use` for each function we want to bring into the
509 `japanese` scope. We could alternatively use the wildcard syntax to include
510 everything from `greetings` into the current scope: `pub use self::greetings::*`.
511
512 What about the `self`? Well, by default, `use` declarations are absolute paths,
513 starting from your crate root. `self` makes that path relative to your current
514 place in the hierarchy instead. There’s one more special form of `use`: you can
515 `use super::` to reach one level up the tree from your current location. Some
516 people like to think of `self` as `.` and `super` as `..`, from many shells’
517 display for the current directory and the parent directory.
518
519 Outside of `use`, paths are relative: `foo::bar()` refers to a function inside
520 of `foo` relative to where we are. If that’s prefixed with `::`, as in
521 `::foo::bar()`, it refers to a different `foo`, an absolute path from your
522 crate root.
523
524 This will build and run:
525
526 ```bash
527 $ cargo run
528 Compiling phrases v0.0.1 (file:///home/you/projects/phrases)
529 Running `target/debug/phrases`
530 Hello in English: Hello!
531 Goodbye in English: Goodbye.
532 Hello in Japanese: こんにちは
533 Goodbye in Japanese: さようなら
534 ```