PageRenderTime 25ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/src/hello-world.md

https://gitlab.com/alx741/book
Markdown | 395 lines | 295 code | 100 blank | 0 comment | 0 complexity | 2aa31a2505648ee929e5937d70a4affd MD5 | raw file
  1. # Hello, world!
  2. Now that you have Rust installed, lets write your first Rust program. It's
  3. traditional when learning a new language to write a little program to print the
  4. text Hello, world! to the screen, and in this section, we'll follow that
  5. tradition.
  6. The nice thing about starting with such a simple program is that you can
  7. quickly verify that your compiler is installed, and that it's working properly.
  8. Printing information to the screen is also just a pretty common thing to do, so
  9. practicing it early on is good.
  10. > Note: This book assumes basic familiarity with the command line. Rust itself
  11. > makes no specific demands about your editing, tooling, or where your code
  12. > lives, so if you prefer an IDE to the command line, that's an option.
  13. ## Creating a Project File
  14. First, make a file to put your Rust code in. Rust doesn't care where your code
  15. lives, but for this book, I suggest making a *projects* directory in your home
  16. directory, and keeping all your projects there. Open a terminal and enter the
  17. following commands to make a directory for this particular project:
  18. ```bash
  19. $ mkdir ~/projects
  20. $ cd ~/projects
  21. $ mkdir hello_world
  22. $ cd hello_world
  23. ```
  24. > Note: If youre on Windows and not using PowerShell, the `~` may not work.
  25. > Consult the documentation for your shell for more details.
  26. ## Writing and Running a Rust Program
  27. Next, make a new source file and call it *main.rs*. Rust files always end
  28. in a *.rs* extension. If youre using more than one word in your filename, use
  29. an underscore to separate them; for example, you'd use *hello_world.rs* rather
  30. than *helloworld.rs*.
  31. Now open the *main.rs* file you just created, and type the following code:
  32. ```rust
  33. fn main() {
  34. println!("Hello, world!");
  35. }
  36. ```
  37. Save the file, and go back to your terminal window. On Linux or OSX, enter the
  38. following commands:
  39. ```bash
  40. $ rustc main.rs
  41. $ ./main
  42. Hello, world!
  43. ```
  44. In Windows, just replace `main` with `main.exe`. Regardless of your operating
  45. system, you should see the string `Hello, world!` print to the terminal. If you
  46. did, then congratulations! You've officially written a Rust program. That makes
  47. you a Rust programmer! Welcome.
  48. ## Anatomy of a Rust Program
  49. Now, lets go over what just happened in your "Hello, world!" program in
  50. detail. Here's the first piece of the puzzle:
  51. ```rust
  52. fn main() {
  53. }
  54. ```
  55. These lines define a *function* in Rust. The `main` function is special: it's
  56. the beginning of every Rust program. The first line says, Im declaring a
  57. function named `main` that takes no arguments and returns nothing. If there
  58. were arguments, they would go inside the parentheses (`(` and `)`), and because
  59. we arent returning anything from this function, we can omit the return type
  60. entirely.
  61. Also note that the function body is wrapped in curly braces (`{` and `}`). Rust
  62. requires these around all function bodies. It's considered good style to put
  63. the opening curly brace on the same line as the function declaration, with one
  64. space in between.
  65. Inside the `main()` function:
  66. ```rust
  67. println!("Hello, world!");
  68. ```
  69. This line does all of the work in this little program: it prints text to the
  70. screen. There are a number of details that are important here. The first is
  71. that its indented with four spaces, not tabs.
  72. The second important part is the `println!()` line. This is calling a Rust
  73. *[macro]*, which is how metaprogramming is done in Rust. If it were calling a
  74. function instead, it would look like this: `println()` (without the !). We'll
  75. discuss Rust macros in more detail later, but for now you just need to
  76. know that when you see a `!` that means that youre calling a macro instead of
  77. a normal function.
  78. [macro]: macros.html
  79. Next is `"Hello, world!"` which is a *string*. We pass this string as an
  80. argument to `println!`, which prints the string to the screen. Easy enough!
  81. The line ends with a semicolon (`;`). Rust is an *expression oriented*
  82. language, which means that most things are expressions, rather than statements.
  83. The `;` indicates that this expression is over, and the next one is ready to
  84. begin. Most lines of Rust code end with a `;`.
  85. ## Compiling and Running Are Separate Steps
  86. In "Writing and Running a Rust Program", we showed you how to run a newly
  87. created program. We'll break that process down and examine each step now.
  88. Before running a Rust program, you have to compile it. You can use the Rust
  89. compiler by entering the `rustc` command and passing it the name of your source
  90. file, like this:
  91. ```bash
  92. $ rustc main.rs
  93. ```
  94. If you come from a C or C++ background, you'll notice that this is similar to
  95. `gcc` or `clang`. After compiling successfully, Rust should output a binary
  96. executable, which you can see on Linux or OSX by entering the `ls` command in
  97. your shell as follows:
  98. ```bash
  99. $ ls
  100. main main.rs
  101. ```
  102. On Windows, you'd enter:
  103. ```bash
  104. $ dir
  105. main.exe main.rs
  106. ```
  107. This shows we have two files: the source code, with an `.rs` extension, and the
  108. executable (`main.exe` on Windows, `main` everywhere else). All that's left to
  109. do from here is run the `main` or `main.exe` file, like this:
  110. ```bash
  111. $ ./main # or main.exe on Windows
  112. ```
  113. If *main.rs* were your "Hello, world!" program, this would print `Hello,
  114. world!` to your terminal.
  115. If you come from a dynamic language like Ruby, Python, or JavaScript, you may
  116. not be used to compiling and running a program being separate steps. Rust is an
  117. *ahead-of-time compiled* language, which means that you can compile a program,
  118. give it to someone else, and they can run it even without Rust installed. If
  119. you give someone a `.rb` or `.py` or `.js` file, on the other hand, they need
  120. to have a Ruby, Python, or JavaScript implementation installed (respectively),
  121. but you only need one command to both compile and run your program. Everything
  122. is a tradeoff in language design.
  123. Just compiling with `rustc` is fine for simple programs, but as your project
  124. grows, you'll want to be able to manage all of the options your project has,
  125. and make it easy to share your code with other people and projects. Next, I'll
  126. introduce you to a tool called Cargo, which will help you write real-world Rust
  127. programs.
  128. # Hello, Cargo!
  129. Cargo is Rusts build system and package manager, and Rustaceans use Cargo to
  130. manage their Rust projects. Cargo manages three things: building your code,
  131. downloading the libraries your code depends on, and building those libraries.
  132. We call libraries your code needs dependencies since your code depends on
  133. them.
  134. The simplest Rust programs dont have any dependencies, so right now, you'd
  135. only use the first part of its functionality. As you write more complex Rust
  136. programs, youll want to add dependencies, and if you start off using Cargo,
  137. that will be a lot easier to do.
  138. As the vast, vast majority of Rust projects use Cargo, we will assume that
  139. youre using it for the rest of the book. Cargo comes installed with Rust
  140. itself, if you used the official installers. If you installed Rust through some
  141. other means, you can check if you have Cargo installed by typing:
  142. ```bash
  143. $ cargo --version
  144. ```
  145. Into a terminal. If you see a version number, great! If you see an error like
  146. `command not found`, then you should look at the documentation for the system
  147. in which you installed Rust, to determine if Cargo is separate.
  148. ## Converting to Cargo
  149. Lets convert the Hello World program to Cargo. To Cargo-fy a project, you need
  150. to do three things:
  151. 1. Put your source file in the right directory.
  152. 2. Get rid of the old executable (`main.exe` on Windows, `main` everywhere else)
  153. and make a new one.
  154. 3. Make a Cargo configuration file.
  155. Let's get started!
  156. ### Creating a new Executable and Source Directory
  157. First, go back to your terminal, move to your *hello_world* directory, and
  158. enter the following commands:
  159. ```bash
  160. $ mkdir src
  161. $ mv main.rs src/main.rs # or 'move main.rs src/main.rs' on Windows
  162. $ rm main # or 'del main.exe' on Windows
  163. ```
  164. Cargo expects your source files to live inside a *src* directory, so do that
  165. first. This leaves the top-level project directory (in this case,
  166. *hello_world*) for READMEs, license information, and anything else not related
  167. to your code. In this way, using Cargo helps you keep your projects nice and
  168. tidy. There's a place for everything, and everything is in its place.
  169. Now, copy *main.rs* to the *src* directory, and delete the compiled file you
  170. created with `rustc`. As usual, replace `main` with `main.exe` if you're on
  171. Windows.
  172. This example retains `main.rs` as the source filename because it's creating an
  173. executable. If you wanted to make a library instead, you'd name the file
  174. `lib.rs`. This convention is used by Cargo to successfully compile your
  175. projects, but it can be overridden if you wish.
  176. ### Creating a Configuration File
  177. Next, create a new file inside your *hello_world* directory, and call it
  178. `Cargo.toml`.
  179. Make sure to capitalize the `C` in `Cargo.toml`, or Cargo won't know what to do
  180. with the configuration file.
  181. This file is in the *[TOML]* (Tom's Obvious, Minimal Language) format. TOML is
  182. similar to INI, but has some extra goodies, and is used as Cargos
  183. configuration format.
  184. [TOML]: https://github.com/toml-lang/toml
  185. Inside this file, type the following information:
  186. ```toml
  187. [package]
  188. name = "hello_world"
  189. version = "0.1.0"
  190. authors = [ "Your name <you@example.com>" ]
  191. ```
  192. The first line, `[package]`, indicates that the following statements are
  193. configuring a package. As we add more information to this file, well add other
  194. sections, but for now, we just have the package configuration.
  195. The other three lines set the three bits of configuration that Cargo needs to
  196. know to compile your program: its name, what version it is, and who wrote it.
  197. Once you've added this information to the *Cargo.toml* file, save it to finish
  198. creating the configuration file.
  199. ## Building and Running a Cargo Project
  200. With your *Cargo.toml* file in place in your project's root directory, you
  201. should be ready to build and run your Hello World program! To do so, enter the
  202. following commands:
  203. ```bash
  204. $ cargo build
  205. Compiling hello_world v0.1.0 (file:///home/yourname/projects/hello_world)
  206. $ ./target/debug/hello_world
  207. Hello, world!
  208. ```
  209. Bam! If all goes well, `Hello, world!` should print to the terminal once more.
  210. You just built a project with `cargo build` and ran it with
  211. `./target/debug/hello_world`, but you can actually do both in one step with
  212. `cargo run` as follows:
  213. ```bash
  214. $ cargo run
  215. Running `target/debug/hello_world`
  216. Hello, world!
  217. ```
  218. Notice that this example didnt re-build the project. Cargo figured out that
  219. the file hasnt changed, and so it just ran the binary. If you'd modified your
  220. source code, Cargo would have rebuilt the project before running it, and you
  221. would have seen something like this:
  222. ```bash
  223. $ cargo run
  224. Compiling hello_world v0.1.0 (file:///home/yourname/projects/hello_world)
  225. Running `target/debug/hello_world`
  226. Hello, world!
  227. ```
  228. Cargo checks to see if any of your projects files have been modified, and only
  229. rebuilds your project if theyve changed since the last time you built it.
  230. With simple projects, Cargo doesn't bring a whole lot over just using `rustc`,
  231. but it will become useful in the future. With complex projects composed of multiple
  232. crates, its much easier to let Cargo coordinate the build. With Cargo, you can
  233. just run `cargo build`, and it should work the right way.
  234. ## Building for Release
  235. When your project is finally ready for release, you can use `cargo build
  236. --release` to compile your project with optimizations. These optimizations make
  237. your Rust code run faster, but turning them on makes your program take longer
  238. to compile. This is why there are two different profiles, one for development,
  239. and one for building the final program youll give to a user.
  240. Running this command also causes Cargo to create a new file called
  241. *Cargo.lock*, which looks like this:
  242. ```toml
  243. [root]
  244. name = "hello_world"
  245. version = "0.1.0"
  246. ```
  247. Cargo uses the *Cargo.lock* file to keep track of dependencies in your
  248. application. This is the Hello World project's *Cargo.lock* file. This project
  249. doesn't have dependencies, so the file is a bit sparse. Realistically, you
  250. won't ever need to touch this file yourself; just let Cargo handle it.
  251. Thats it! If you've been following along, you should have successfully built
  252. `hello_world` with Cargo.
  253. Even though the project is simple, it now uses much of the real tooling youll
  254. use for the rest of your Rust career. In fact, you can expect to start
  255. virtually all Rust projects with some variation on the following commands:
  256. ```bash
  257. $ git clone someurl.com/foo
  258. $ cd foo
  259. $ cargo build
  260. ```
  261. ## Making A New Cargo Project the Easy Way
  262. You dont have to go through that previous process every time you want to start
  263. a new project! Cargo can quickly make a bare-bones project directory that you
  264. can start developing in right away.
  265. To start a new project with Cargo, enter `cargo new` at the command line:
  266. ```bash
  267. $ cargo new hello_world --bin
  268. ```
  269. This command passes `--bin` because the goal is to get straight to making an
  270. executable application, as opposed to a library. Executables are often called
  271. *binaries* (as in `/usr/bin`, if youre on a Unix system).
  272. Cargo has generated two files and one directory for us: a `Cargo.toml` and a
  273. *src* directory with a *main.rs* file inside. These should look familliar,
  274. theyre exactly what we created by hand, above.
  275. This output is all you need to get started. First, open `Cargo.toml`. It should
  276. look something like this:
  277. ```toml
  278. [package]
  279. name = "hello_world"
  280. version = "0.1.0"
  281. authors = ["Your Name <you@example.com>"]
  282. ```
  283. Cargo has populated *Cargo.toml* with reasonable defaults based on the arguments
  284. you gave it and your `git` global configuration. You may notice that Cargo has
  285. also initialized the `hello_world` directory as a `git` repository.
  286. Heres what should be in `src/main.rs`:
  287. ```rust
  288. fn main() {
  289. println!("Hello, world!");
  290. }
  291. ```
  292. Cargo has generated a "Hello World!" for you, and youre ready to start coding!
  293. > Note: If you want to look at Cargo in more detail, check out the official [Cargo
  294. guide], which covers all of its features.
  295. [Cargo guide]: http://doc.crates.io/guide.html