Sophie

Sophie

distrib > Mageia > 6 > armv7hl > media > core-updates > by-pkgid > 4e2dbb669434a7691662cb2f0ad38972 > files > 662

rust-doc-1.28.0-1.mga6.armv7hl.rpm

<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>Getting Started - The Rust Programming Language</title>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <base href="">

        <link rel="stylesheet" href="book.css">
        <link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
        <link href="https://fonts.googleapis.com/css?family=Source+Code+Pro:500" rel="stylesheet" type="text/css">

        <link rel="shortcut icon" href="favicon.png">

        <!-- Font Awesome -->
        <link rel="stylesheet" href="_FontAwesome/css/font-awesome.css">

        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <link rel="stylesheet" href="ayu-highlight.css">

        <!-- Custom theme stylesheets -->
        
        <link rel="stylesheet" href="src/theme/first-edition.css">
        

        

    </head>
    <body class="light">
        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { } 
            if (theme === null || theme === undefined) { theme = 'light'; }
            document.body.className = theme;
            document.querySelector('html').className = theme + ' js';
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <ol class="chapter"><li class="affix"><a href="README.html">Introduction</a></li><li><a href="getting-started.html" class="active"><strong aria-hidden="true">1.</strong> Getting Started</a></li><li><a href="guessing-game.html"><strong aria-hidden="true">2.</strong> Tutorial: Guessing Game</a></li><li><a href="syntax-and-semantics.html"><strong aria-hidden="true">3.</strong> Syntax and Semantics</a></li><li><ol class="section"><li><a href="variable-bindings.html"><strong aria-hidden="true">3.1.</strong> Variable Bindings</a></li><li><a href="functions.html"><strong aria-hidden="true">3.2.</strong> Functions</a></li><li><a href="primitive-types.html"><strong aria-hidden="true">3.3.</strong> Primitive Types</a></li><li><a href="comments.html"><strong aria-hidden="true">3.4.</strong> Comments</a></li><li><a href="if.html"><strong aria-hidden="true">3.5.</strong> if</a></li><li><a href="loops.html"><strong aria-hidden="true">3.6.</strong> Loops</a></li><li><a href="vectors.html"><strong aria-hidden="true">3.7.</strong> Vectors</a></li><li><a href="ownership.html"><strong aria-hidden="true">3.8.</strong> Ownership</a></li><li><a href="references-and-borrowing.html"><strong aria-hidden="true">3.9.</strong> References and Borrowing</a></li><li><a href="lifetimes.html"><strong aria-hidden="true">3.10.</strong> Lifetimes</a></li><li><a href="mutability.html"><strong aria-hidden="true">3.11.</strong> Mutability</a></li><li><a href="structs.html"><strong aria-hidden="true">3.12.</strong> Structs</a></li><li><a href="enums.html"><strong aria-hidden="true">3.13.</strong> Enums</a></li><li><a href="match.html"><strong aria-hidden="true">3.14.</strong> Match</a></li><li><a href="patterns.html"><strong aria-hidden="true">3.15.</strong> Patterns</a></li><li><a href="method-syntax.html"><strong aria-hidden="true">3.16.</strong> Method Syntax</a></li><li><a href="strings.html"><strong aria-hidden="true">3.17.</strong> Strings</a></li><li><a href="generics.html"><strong aria-hidden="true">3.18.</strong> Generics</a></li><li><a href="traits.html"><strong aria-hidden="true">3.19.</strong> Traits</a></li><li><a href="drop.html"><strong aria-hidden="true">3.20.</strong> Drop</a></li><li><a href="if-let.html"><strong aria-hidden="true">3.21.</strong> if let</a></li><li><a href="trait-objects.html"><strong aria-hidden="true">3.22.</strong> Trait Objects</a></li><li><a href="closures.html"><strong aria-hidden="true">3.23.</strong> Closures</a></li><li><a href="ufcs.html"><strong aria-hidden="true">3.24.</strong> Universal Function Call Syntax</a></li><li><a href="crates-and-modules.html"><strong aria-hidden="true">3.25.</strong> Crates and Modules</a></li><li><a href="const-and-static.html"><strong aria-hidden="true">3.26.</strong> const and static</a></li><li><a href="attributes.html"><strong aria-hidden="true">3.27.</strong> Attributes</a></li><li><a href="type-aliases.html"><strong aria-hidden="true">3.28.</strong> type aliases</a></li><li><a href="casting-between-types.html"><strong aria-hidden="true">3.29.</strong> Casting between types</a></li><li><a href="associated-types.html"><strong aria-hidden="true">3.30.</strong> Associated Types</a></li><li><a href="unsized-types.html"><strong aria-hidden="true">3.31.</strong> Unsized Types</a></li><li><a href="operators-and-overloading.html"><strong aria-hidden="true">3.32.</strong> Operators and Overloading</a></li><li><a href="deref-coercions.html"><strong aria-hidden="true">3.33.</strong> Deref coercions</a></li><li><a href="macros.html"><strong aria-hidden="true">3.34.</strong> Macros</a></li><li><a href="raw-pointers.html"><strong aria-hidden="true">3.35.</strong> Raw Pointers</a></li><li><a href="unsafe.html"><strong aria-hidden="true">3.36.</strong> unsafe</a></li></ol></li><li><a href="effective-rust.html"><strong aria-hidden="true">4.</strong> Effective Rust</a></li><li><ol class="section"><li><a href="the-stack-and-the-heap.html"><strong aria-hidden="true">4.1.</strong> The Stack and the Heap</a></li><li><a href="testing.html"><strong aria-hidden="true">4.2.</strong> Testing</a></li><li><a href="conditional-compilation.html"><strong aria-hidden="true">4.3.</strong> Conditional Compilation</a></li><li><a href="documentation.html"><strong aria-hidden="true">4.4.</strong> Documentation</a></li><li><a href="iterators.html"><strong aria-hidden="true">4.5.</strong> Iterators</a></li><li><a href="concurrency.html"><strong aria-hidden="true">4.6.</strong> Concurrency</a></li><li><a href="error-handling.html"><strong aria-hidden="true">4.7.</strong> Error Handling</a></li><li><a href="choosing-your-guarantees.html"><strong aria-hidden="true">4.8.</strong> Choosing your Guarantees</a></li><li><a href="ffi.html"><strong aria-hidden="true">4.9.</strong> FFI</a></li><li><a href="borrow-and-asref.html"><strong aria-hidden="true">4.10.</strong> Borrow and AsRef</a></li><li><a href="release-channels.html"><strong aria-hidden="true">4.11.</strong> Release Channels</a></li><li><a href="using-rust-without-the-standard-library.html"><strong aria-hidden="true">4.12.</strong> Using Rust without the standard library</a></li><li><a href="procedural-macros.html"><strong aria-hidden="true">4.13.</strong> Procedural Macros (and custom derive)</a></li></ol></li><li><a href="glossary.html"><strong aria-hidden="true">5.</strong> Glossary</a></li><li><a href="syntax-index.html"><strong aria-hidden="true">6.</strong> Syntax Index</a></li><li><a href="bibliography.html"><strong aria-hidden="true">7.</strong> Bibliography</a></li></ol>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                <div id="draft-warning" class="warning">
    <span class="message">You are reading an <strong>outdated</strong> edition of TRPL. For more, go <a href="../index.html">here</a>.</span>
    <button type="button" id="hide-draft-warning" title="Hide draft warning" class="button">
        <i class="fa fa-times"></i>
    </button>
</div>
<!-- Hide / unhide warning before it is displayed -->
<script type="text/javascript">
var warning = localStorage.getItem('trpl-first-edition-draft-warning');

if (warning === 'hidden') {
    Array
    .from(document.querySelectorAll('#page-wrapper'))
    .forEach(function(block) { block.classList.remove('has-warning'); });
    var elem = document.getElementById("draft-warning");
    elem.parentNode.removeChild(elem);
}

document.addEventListener("DOMContentLoaded", function(event) { 
    document.getElementById("hide-draft-warning").addEventListener("click", function(e) {
        var elem = document.getElementById("draft-warning");
        elem.parentNode.removeChild(elem);

        localStorage.setItem('trpl-first-edition-draft-warning', 'hidden');
    });
});
</script>

                <div id="menu-bar" class="menu-bar">
                    <div id="menu-bar-sticky-container">
                        <div class="left-buttons">
                            <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                                <i class="fa fa-bars"></i>
                            </button>
                            <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                                <i class="fa fa-paint-brush"></i>
                            </button>
                            <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                                <li role="none"><button role="menuitem" class="theme" id="light">Light <span class="default">(default)</span></button></li>
                                <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                                <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                                <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                                <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                            </ul>
                            
                            <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                                <i class="fa fa-search"></i>
                            </button>
                            
                        </div>

                        <h1 class="menu-title">The Rust Programming Language</h1> 

                        <div class="right-buttons">
                            <a href="print.html" title="Print this book" aria-label="Print this book">
                                <i id="print-button" class="fa fa-print"></i>
                            </a>
                        </div>
                    </div>
                </div>

                
                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" name="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>
                

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <a class="header" href="getting-started.html#getting-started" id="getting-started"><h1>Getting Started</h1></a>
<p>This first chapter of the book will get us going with Rust and its tooling.
First, we’ll install Rust. Then, the classic ‘Hello World’ program. Finally,
we’ll talk about Cargo, Rust’s build system and package manager.</p>
<p>We’ll be showing off a number of commands using a terminal, and those lines all
start with <code>$</code>. You don't need to type in the <code>$</code>s, they are there to indicate
the start of each command. We’ll see many tutorials and examples around the web
that follow this convention: <code>$</code> for commands run as our regular user, and <code>#</code>
for commands we should be running as an administrator.</p>
<a class="header" href="getting-started.html#installing-rust" id="installing-rust"><h1>Installing Rust</h1></a>
<p>The first step to using Rust is to install it. Generally speaking, you’ll need
an Internet connection to run the commands in this section, as we’ll be
downloading Rust from the Internet.</p>
<p>The Rust compiler runs on, and compiles to, a great number of platforms, but is
best supported on Linux, Mac, and Windows, on the x86 and x86-64 CPU
architecture. There are official builds of the Rust compiler and standard
library for these platforms and more. <a href="https://forge.rust-lang.org/platform-support.html">For full details on Rust platform support
see the website</a>.</p>
<a class="header" href="getting-started.html#installing-rust-1" id="installing-rust-1"><h2>Installing Rust</h2></a>
<p>All you need to do on Unix systems like Linux and macOS is open a
terminal and type this:</p>
<pre><code class="language-bash">$ curl https://sh.rustup.rs -sSf | sh
</code></pre>
<p>It will download a script, and start the installation. If everything
goes well, you’ll see this appear:</p>
<pre><code class="language-text">Rust is installed now. Great! 
</code></pre>
<p>Installing on Windows is nearly as easy: download and run
<a href="https://win.rustup.rs">rustup-init.exe</a>. It will start the installation in a console and
present the above message on success.</p>
<p>For other installation options and information, visit the <a href="https://www.rust-lang.org/install.html">install</a>
page of the Rust website.</p>
<a class="header" href="getting-started.html#uninstalling" id="uninstalling"><h2>Uninstalling</h2></a>
<p>Uninstalling Rust is as easy as installing it:</p>
<pre><code class="language-bash">$ rustup self uninstall
</code></pre>
<a class="header" href="getting-started.html#troubleshooting" id="troubleshooting"><h2>Troubleshooting</h2></a>
<p>If we've got Rust installed, we can open up a shell, and type this:</p>
<pre><code class="language-bash">$ rustc --version
</code></pre>
<p>You should see the version number, commit hash, and commit date.</p>
<p>If you do, Rust has been installed successfully! Congrats!</p>
<p>If you don't, that probably means that the <code>PATH</code> environment variable
doesn't include Cargo's binary directory, <code>~/.cargo/bin</code> on Unix, or
<code>%USERPROFILE%\.cargo\bin</code> on Windows. This is the directory where
Rust development tools live, and most Rust developers keep it in their
<code>PATH</code> environment variable, which makes it possible to run <code>rustc</code> on
the command line. Due to differences in operating systems, command
shells, and bugs in installation, you may need to restart your shell,
log out of the system, or configure <code>PATH</code> manually as appropriate for
your operating environment.</p>
<p>Rust does not do its own linking, and so you’ll need to have a linker
installed. Doing so will depend on your specific system. For
Linux-based systems, Rust will attempt to call <code>cc</code> for linking. On
<code>windows-msvc</code> (Rust built on Windows with Microsoft Visual Studio),
this depends on having <a href="http://landinghub.visualstudio.com/visual-cpp-build-tools">Microsoft Visual C++ Build Tools</a>
installed. These do not need to be in <code>%PATH%</code> as <code>rustc</code> will find
them automatically. In general, if you have your linker in a
non-traditional location you can call <code>rustc linker=/path/to/cc</code>, where <code>/path/to/cc</code> should point to your linker path.</p>
<p>If you are still stuck, there are a number of places where we can get
help. The easiest is
<a href="irc://irc.mozilla.org/#rust-beginners">the #rust-beginners IRC channel on irc.mozilla.org</a>
and for general discussion
<a href="irc://irc.mozilla.org/#rust">the #rust IRC channel on irc.mozilla.org</a>, which we
can access through <a href="http://chat.mibbit.com/?server=irc.mozilla.org&amp;channel=%23rust-beginners,%23rust">Mibbit</a>. Then we'll be chatting with other
Rustaceans (a silly nickname we call ourselves) who can help us out. Other great
resources include <a href="https://users.rust-lang.org/">the user’s forum</a> and <a href="http://stackoverflow.com/questions/tagged/rust">Stack Overflow</a>.</p>
<p>This installer also installs a copy of the documentation locally, so we can
read it offline. It's only a <code>rustup doc</code> away!</p>
<a class="header" href="getting-started.html#hello-world" id="hello-world"><h1>Hello, world!</h1></a>
<p>Now that you have Rust installed, we'll help you write your first Rust program.
It's traditional when learning a new language to write a little program to
print the text “Hello, world!” to the screen, and in this section, we'll follow
that tradition.</p>
<p>The nice thing about starting with such a simple program is that you can
quickly verify that your compiler is installed, and that it's working properly.
Printing information to the screen is also a pretty common thing to do, so
practicing it early on is good.</p>
<blockquote>
<p>Note: This book assumes basic familiarity with the command line. Rust itself
makes no specific demands about your editing, tooling, or where your code
lives, so if you prefer an IDE to the command line, that's an option. You may
want to check out <a href="https://github.com/oakes/SolidOak">SolidOak</a>, which was built specifically with Rust in mind.
There are a number of extensions in development by the community, and the
Rust team ships plugins for <a href="https://github.com/rust-lang/rust/blob/master/src/etc/CONFIGS.md">various editors</a>. Configuring your editor or
IDE is out of the scope of this tutorial, so check the documentation for your
specific setup.</p>
</blockquote>
<a class="header" href="getting-started.html#creating-a-project-file" id="creating-a-project-file"><h2>Creating a Project File</h2></a>
<p>First, make a file to put your Rust code in. Rust doesn't care where your code
lives, but for this book, I suggest making a <em>projects</em> directory in your home
directory, and keeping all your projects there. Open a terminal and enter the
following commands to make a directory for this particular project:</p>
<pre><code class="language-bash">$ mkdir ~/projects
$ cd ~/projects
$ mkdir hello_world
$ cd hello_world
</code></pre>
<blockquote>
<p>Note: If you’re on Windows and not using PowerShell, the <code>~</code> may not work.
Consult the documentation for your shell for more details.</p>
</blockquote>
<a class="header" href="getting-started.html#writing-and-running-a-rust-program" id="writing-and-running-a-rust-program"><h2>Writing and Running a Rust Program</h2></a>
<p>We need to create a source file for our Rust program. Rust files always end
in a <em>.rs</em> extension. If you are using more than one word in your filename,
use an underscore to separate them; for example, you would use
<em>my_program.rs</em> rather than <em>myprogram.rs</em>.</p>
<p>Now, make a new file and call it <em>main.rs</em>. Open the file and type
the following code:</p>
<pre><pre class="playpen"><code class="language-rust">fn main() {
    println!(&quot;Hello, world!&quot;);
}
</code></pre></pre>
<p>Save the file, and go back to your terminal window. On Linux or macOS, enter the
following commands:</p>
<pre><code class="language-bash">$ rustc main.rs
$ ./main
Hello, world!
</code></pre>
<p>In Windows, replace <code>main</code> with <code>main.exe</code>. Regardless of your operating
system, you should see the string <code>Hello, world!</code> print to the terminal. If you
did, then congratulations! You've officially written a Rust program. That makes
you a Rust programmer! Welcome.</p>
<a class="header" href="getting-started.html#anatomy-of-a-rust-program" id="anatomy-of-a-rust-program"><h2>Anatomy of a Rust Program</h2></a>
<p>Now, let’s go over what just happened in your &quot;Hello, world!&quot; program in
detail. Here's the first piece of the puzzle:</p>
<pre><pre class="playpen"><code class="language-rust">fn main() {

}
</code></pre></pre>
<p>These lines define a <em>function</em> in Rust. The <code>main</code> function is special: it's
the beginning of every Rust program. The first line says, “I’m declaring a
function named <code>main</code> that takes no arguments and returns nothing.” If there
were arguments, they would go inside the parentheses (<code>(</code> and <code>)</code>), and because
we aren’t returning anything from this function, we can omit the return type
entirely.</p>
<p>Also note that the function body is wrapped in curly braces (<code>{</code> and <code>}</code>). Rust
requires these around all function bodies. It's considered good style to put
the opening curly brace on the same line as the function declaration, with one
space in between.</p>
<p>Inside the <code>main()</code> function:</p>
<pre><pre class="playpen"><code class="language-rust">
# #![allow(unused_variables)]
#fn main() {
    println!(&quot;Hello, world!&quot;);
#}</code></pre></pre>
<p>This line does all of the work in this little program: it prints text to the
screen. There are a number of details that are important here. The first is
that it’s indented with four spaces, not tabs.</p>
<p>The second important part is the <code>println!()</code> line. This is calling a Rust
<em><a href="macros.html">macro</a></em>, which is how metaprogramming is done in Rust. If it were calling a
function instead, it would look like this: <code>println()</code> (without the !). We'll
discuss Rust macros in more detail later, but for now you only need to
know that when you see a <code>!</code> that means that you’re calling a macro instead of
a normal function.</p>
<p>Next is <code>&quot;Hello, world!&quot;</code> which is a <em>string</em>. Strings are a surprisingly
complicated topic in a systems programming language, and this is a <em><a href="the-stack-and-the-heap.html">statically
allocated</a></em> string. We pass this string as an argument to <code>println!</code>, which
prints the string to the screen. Easy enough!</p>
<p>The line ends with a semicolon (<code>;</code>). Rust is an <em><a href="glossary.html#expression-oriented-language">expression-oriented
language</a></em>, which means that most things are expressions, rather than
statements. The <code>;</code> indicates that this expression is over, and the next one is
ready to begin. Most lines of Rust code end with a <code>;</code>.</p>
<a class="header" href="getting-started.html#compiling-and-running-are-separate-steps" id="compiling-and-running-are-separate-steps"><h2>Compiling and Running Are Separate Steps</h2></a>
<p>In &quot;Writing and Running a Rust Program&quot;, we showed you how to run a newly
created program. We'll break that process down and examine each step now.</p>
<p>Before running a Rust program, you have to compile it. You can use the Rust
compiler by entering the <code>rustc</code> command and passing it the name of your source
file, like this:</p>
<pre><code class="language-bash">$ rustc main.rs
</code></pre>
<p>If you come from a C or C++ background, you'll notice that this is similar to
<code>gcc</code> or <code>clang</code>. After compiling successfully, Rust should output a binary
executable, which you can see on Linux or macOS by entering the <code>ls</code> command in
your shell as follows:</p>
<pre><code class="language-bash">$ ls
main  main.rs
</code></pre>
<p>On Windows, you'd enter:</p>
<pre><code class="language-bash">$ dir
main.exe
main.rs
</code></pre>
<p>This shows we have two files: the source code, with an <code>.rs</code> extension, and the
executable (<code>main.exe</code> on Windows, <code>main</code> everywhere else). All that's left to
do from here is run the <code>main</code> or <code>main.exe</code> file, like this:</p>
<pre><code class="language-bash">$ ./main  # or .\main.exe on Windows
</code></pre>
<p>If <em>main.rs</em> were your &quot;Hello, world!&quot; program, this would print <code>Hello, world!</code> to your terminal.</p>
<p>If you come from a dynamic language like Ruby, Python, or JavaScript, you may
not be used to compiling and running a program being separate steps. Rust is an
<em>ahead-of-time compiled</em> language, which means that you can compile a program,
give it to someone else, and they can run it even without Rust installed. If
you give someone a <code>.rb</code> or <code>.py</code> or <code>.js</code> file, on the other hand, they need
to have a Ruby, Python, or JavaScript implementation installed (respectively),
but you only need one command to both compile and run your program. Everything
is a tradeoff in language design.</p>
<p>Just compiling with <code>rustc</code> is fine for simple programs, but as your project
grows, you'll want to be able to manage all of the options your project has,
and make it easy to share your code with other people and projects. Next, I'll
introduce you to a tool called Cargo, which will help you write real-world Rust
programs.</p>
<a class="header" href="getting-started.html#hello-cargo" id="hello-cargo"><h1>Hello, Cargo!</h1></a>
<p>Cargo is Rust’s build system and package manager, and Rustaceans use Cargo to
manage their Rust projects. Cargo manages three things: building your code,
downloading the libraries your code depends on, and building those libraries.
We call libraries your code needs ‘dependencies’ since your code depends on
them.</p>
<p>The simplest Rust programs don’t have any dependencies, so right now, you'd
only use the first part of its functionality. As you write more complex Rust
programs, you’ll want to add dependencies, and if you start off using Cargo,
that will be a lot easier to do.</p>
<p>As the vast, vast majority of Rust projects use Cargo, we will assume that
you’re using it for the rest of the book. Cargo comes installed with Rust
itself, if you used the official installers. If you installed Rust through some
other means, you can check if you have Cargo installed by typing:</p>
<pre><code class="language-bash">$ cargo --version
</code></pre>
<p>Into a terminal. If you see a version number, great! If you see an error like
‘<code>command not found</code>’, then you should look at the documentation for the system
in which you installed Rust, to determine if Cargo is separate.</p>
<a class="header" href="getting-started.html#converting-to-cargo" id="converting-to-cargo"><h2>Converting to Cargo</h2></a>
<p>Let’s convert the Hello World program to Cargo. To Cargo-fy a project, you need
to do three things:</p>
<ol>
<li>Put your source file in the right directory.</li>
<li>Get rid of the old executable (<code>main.exe</code> on Windows, <code>main</code> everywhere
else).</li>
<li>Make a Cargo configuration file.</li>
</ol>
<p>Let's get started!</p>
<a class="header" href="getting-started.html#creating-a-source-directory-and-removing-the-old-executable" id="creating-a-source-directory-and-removing-the-old-executable"><h3>Creating a Source Directory and Removing the Old Executable</h3></a>
<p>First, go back to your terminal, move to your <em>hello_world</em> directory, and
enter the following commands:</p>
<pre><code class="language-bash">$ mkdir src
$ mv main.rs src/main.rs # or 'move main.rs src/main.rs' on Windows
$ rm main  # or 'del main.exe' on Windows
</code></pre>
<p>Cargo expects your source files to live inside a <em>src</em> directory, so do that
first. This leaves the top-level project directory (in this case,
<em>hello_world</em>) for READMEs, license information, and anything else not related
to your code. In this way, using Cargo helps you keep your projects nice and
tidy. There's a place for everything, and everything is in its place.</p>
<p>Now, move <em>main.rs</em> into the <em>src</em> directory, and delete the compiled file you
created with <code>rustc</code>. As usual, replace <code>main</code> with <code>main.exe</code> if you're on
Windows.</p>
<p>This example retains <code>main.rs</code> as the source filename because it's creating an
executable. If you wanted to make a library instead, you'd name the file
<code>lib.rs</code>. This convention is used by Cargo to successfully compile your
projects, but it can be overridden if you wish.</p>
<a class="header" href="getting-started.html#creating-a-configuration-file" id="creating-a-configuration-file"><h3>Creating a Configuration File</h3></a>
<p>Next, create a new file inside your <em>hello_world</em> directory, and call it
<code>Cargo.toml</code>.</p>
<p>Make sure to capitalize the <code>C</code> in <code>Cargo.toml</code>, or Cargo won't know what to do
with the configuration file.</p>
<p>This file is in the <em><a href="https://github.com/toml-lang/toml">TOML</a></em> (Tom's Obvious, Minimal Language) format. TOML is
similar to INI, but has some extra goodies, and is used as Cargo’s
configuration format.</p>
<p>Inside this file, type the following information:</p>
<pre><code class="language-toml">[package]

name = &quot;hello_world&quot;
version = &quot;0.0.1&quot;
authors = [ &quot;Your name &lt;you@example.com&gt;&quot; ]
</code></pre>
<p>The first line, <code>[package]</code>, indicates that the following statements are
configuring a package. As we add more information to this file, we’ll add other
sections, but for now, we only have the package configuration.</p>
<p>The other three lines set the three bits of configuration that Cargo needs to
know to compile your program: its name, what version it is, and who wrote it.</p>
<p>Once you've added this information to the <em>Cargo.toml</em> file, save it to finish
creating the configuration file.</p>
<a class="header" href="getting-started.html#building-and-running-a-cargo-project" id="building-and-running-a-cargo-project"><h2>Building and Running a Cargo Project</h2></a>
<p>With your <em>Cargo.toml</em> file in place in your project's root directory, you
should be ready to build and run your Hello World program! To do so, enter the
following commands:</p>
<pre><code class="language-bash">$ cargo build
   Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world)
$ ./target/debug/hello_world
Hello, world!
</code></pre>
<p>Bam! If all goes well, <code>Hello, world!</code> should print to the terminal once more.</p>
<p>You just built a project with <code>cargo build</code> and ran it with
<code>./target/debug/hello_world</code>, but you can actually do both in one step with
<code>cargo run</code> as follows:</p>
<pre><code class="language-bash">$ cargo run
     Running `target/debug/hello_world`
Hello, world!
</code></pre>
<p>The <code>run</code> command comes in handy when you need to rapidly iterate on a
project.</p>
<p>Notice that this example didn’t re-build the project. Cargo figured out that
the file hasn’t changed, and so it just ran the binary. If you'd modified your
source code, Cargo would have rebuilt the project before running it, and you
would have seen something like this:</p>
<pre><code class="language-bash">$ cargo run
   Compiling hello_world v0.0.1 (file:///home/yourname/projects/hello_world)
     Running `target/debug/hello_world`
Hello, world!
</code></pre>
<p>Cargo checks to see if any of your project’s files have been modified, and only
rebuilds your project if they’ve changed since the last time you built it.</p>
<p>With simple projects, Cargo doesn't bring a whole lot over just using <code>rustc</code>,
but it will become useful in the future. This is especially true when you start
using crates; these are synonymous with a ‘library’ or ‘package’ in other
programming languages. For complex projects composed of multiple crates, it’s
much easier to let Cargo coordinate the build. Using Cargo, you can run <code>cargo build</code>, and it should work the right way.</p>
<a class="header" href="getting-started.html#building-for-release" id="building-for-release"><h3>Building for Release</h3></a>
<p>When your project is ready for release, you can use <code>cargo build --release</code> to compile your project with optimizations. These optimizations make
your Rust code run faster, but turning them on makes your program take longer
to compile. This is why there are two different profiles, one for development,
and one for building the final program you’ll give to a user.</p>
<a class="header" href="getting-started.html#what-is-that-cargolock" id="what-is-that-cargolock"><h3>What Is That <code>Cargo.lock</code>?</h3></a>
<p>Running <code>cargo build</code> also causes Cargo to create a new file called
<em>Cargo.lock</em>, which looks like this:</p>
<pre><code class="language-toml">[root]
name = &quot;hello_world&quot;
version = &quot;0.0.1&quot;
</code></pre>
<p>Cargo uses the <em>Cargo.lock</em> file to keep track of dependencies in your
application. This is the Hello World project's <em>Cargo.lock</em> file. This project
doesn't have dependencies, so the file is a bit sparse. Realistically, you
won't ever need to touch this file yourself; just let Cargo handle it.</p>
<p>That’s it! If you've been following along, you should have successfully built
<code>hello_world</code> with Cargo.</p>
<p>Even though the project is simple, it now uses much of the real tooling you’ll
use for the rest of your Rust career. In fact, you can expect to start
virtually all Rust projects with some variation on the following commands:</p>
<pre><code class="language-bash">$ git clone someurl.com/foo
$ cd foo
$ cargo build
</code></pre>
<a class="header" href="getting-started.html#making-a-new-cargo-project-the-easy-way" id="making-a-new-cargo-project-the-easy-way"><h2>Making A New Cargo Project the Easy Way</h2></a>
<p>You don’t have to go through that previous process every time you want to start
a new project! Cargo can quickly make a bare-bones project directory that you
can start developing in right away.</p>
<p>To start a new project with Cargo, enter <code>cargo new</code> at the command line:</p>
<pre><code class="language-bash">$ cargo new hello_world --bin
</code></pre>
<p>This command passes <code>--bin</code> because the goal is to get straight to making an
executable application, as opposed to a library. Executables are often called
<em>binaries</em> (as in <code>/usr/bin</code>, if you’re on a Unix system).</p>
<p>Cargo has generated two files and one directory for us: a <code>Cargo.toml</code> and a
<em>src</em> directory with a <em>main.rs</em> file inside. These should look familiar,
they’re exactly what we created by hand, above.</p>
<p>This output is all you need to get started. First, open <code>Cargo.toml</code>. It should
look something like this:</p>
<pre><code class="language-toml">[package]

name = &quot;hello_world&quot;
version = &quot;0.1.0&quot;
authors = [&quot;Your Name &lt;you@example.com&gt;&quot;]

[dependencies]
</code></pre>
<p>Do not worry about the <code>[dependencies]</code> line, we will come back to it later.</p>
<p>Cargo has populated <em>Cargo.toml</em> with reasonable defaults based on the arguments
you gave it and your <code>git</code> global configuration. You may notice that Cargo has
also initialized the <code>hello_world</code> directory as a <code>git</code> repository.</p>
<p>Here’s what should be in <code>src/main.rs</code>:</p>
<pre><pre class="playpen"><code class="language-rust">fn main() {
    println!(&quot;Hello, world!&quot;);
}
</code></pre></pre>
<p>Cargo has generated a &quot;Hello World!&quot; for you, and you’re ready to start coding!</p>
<blockquote>
<p>Note: If you want to look at Cargo in more detail, check out the official <a href="http://doc.crates.io/guide.html">Cargo
guide</a>, which covers all of its features.</p>
</blockquote>
<a class="header" href="getting-started.html#closing-thoughts" id="closing-thoughts"><h1>Closing Thoughts</h1></a>
<p>This chapter covered the basics that will serve you well through the rest of
this book, and the rest of your time with Rust. Now that you’ve got the tools
down, we'll cover more about the Rust language itself.</p>
<p>You have two options: Dive into a project with ‘<a href="guessing-game.html">Tutorial: Guessing Game</a>’, or
start from the bottom and work your way up with ‘<a href="syntax-and-semantics.html">Syntax and
Semantics</a>’. More experienced systems programmers will probably prefer
‘Tutorial: Guessing Game’, while those from dynamic backgrounds may enjoy either. Different
people learn differently! Choose whatever’s right for you.</p>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                        
                            <a rel="prev" href="README.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>
                        

                        
                            <a rel="next" href="guessing-game.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>
                        

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                
                    <a href="README.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>
                

                
                    <a href="guessing-game.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
                
            </nav>

        </div>

        

        

        

        

        
        <script src="searchindex.js" type="text/javascript" charset="utf-8"></script>
        
        
        <script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="searcher.js" type="text/javascript" charset="utf-8"></script>
        

        <script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->
        

    </body>
</html>