]> git.proxmox.com Git - rustc.git/blob - src/tools/cargo/src/doc/src/guide/creating-a-new-project.md
New upstream version 1.74.1+dfsg1
[rustc.git] / src / tools / cargo / src / doc / src / guide / creating-a-new-project.md
1 # Creating a New Package
2
3 To start a new [package][def-package] with Cargo, use `cargo new`:
4
5 ```console
6 $ cargo new hello_world --bin
7 ```
8
9 We’re passing `--bin` because we’re making a binary program: if we
10 were making a library, we’d pass `--lib`. This also initializes a new `git`
11 repository by default. If you don't want it to do that, pass `--vcs none`.
12
13 Let’s check out what Cargo has generated for us:
14
15 ```console
16 $ cd hello_world
17 $ tree .
18 .
19 ├── Cargo.toml
20 └── src
21 └── main.rs
22
23 1 directory, 2 files
24 ```
25
26 Let’s take a closer look at `Cargo.toml`:
27
28 ```toml
29 [package]
30 name = "hello_world"
31 version = "0.1.0"
32 edition = "2021"
33
34 [dependencies]
35
36 ```
37
38 This is called a [***manifest***][def-manifest], and it contains all of the
39 metadata that Cargo needs to compile your package. This file is written in the
40 [TOML] format (pronounced /tɑməl/).
41
42 Here’s what’s in `src/main.rs`:
43
44 ```rust
45 fn main() {
46 println!("Hello, world!");
47 }
48 ```
49
50 Cargo generated a “hello world” program for us, otherwise known as a
51 [*binary crate*][def-crate]. Let’s compile it:
52
53 ```console
54 $ cargo build
55 Compiling hello_world v0.1.0 (file:///path/to/package/hello_world)
56 ```
57
58 And then run it:
59
60 ```console
61 $ ./target/debug/hello_world
62 Hello, world!
63 ```
64
65 We can also use `cargo run` to compile and then run it, all in one step (You
66 won't see the `Compiling` line if you have not made any changes since you last
67 compiled):
68
69 ```console
70 $ cargo run
71 Compiling hello_world v0.1.0 (file:///path/to/package/hello_world)
72 Running `target/debug/hello_world`
73 Hello, world!
74 ```
75
76 You’ll now notice a new file, `Cargo.lock`. It contains information about our
77 dependencies. Since we don’t have any yet, it’s not very interesting.
78
79 Once you’re ready for release, you can use `cargo build --release` to compile
80 your files with optimizations turned on:
81
82 ```console
83 $ cargo build --release
84 Compiling hello_world v0.1.0 (file:///path/to/package/hello_world)
85 ```
86
87 `cargo build --release` puts the resulting binary in `target/release` instead of
88 `target/debug`.
89
90 Compiling in debug mode is the default for development. Compilation time is
91 shorter since the compiler doesn't do optimizations, but the code will run
92 slower. Release mode takes longer to compile, but the code will run faster.
93
94 [TOML]: https://toml.io/
95 [def-crate]: ../appendix/glossary.md#crate '"crate" (glossary entry)'
96 [def-manifest]: ../appendix/glossary.md#manifest '"manifest" (glossary entry)'
97 [def-package]: ../appendix/glossary.md#package '"package" (glossary entry)'