Hello, Cargo! - The Rust Programming Language (2023)

Hello, Cargo!

Cargo is Rust’s build system and package manager. Most Rustaceans use this toolto manage their Rust projects because Cargo handles a lot of tasks for you,such as building your code, downloading the libraries your code depends on, andbuilding those libraries. (We call the libraries that your code needsdependencies.)

The simplest Rust programs, like the one we’ve written so far, don’t have anydependencies. If we had built the “Hello, world!” project with Cargo, it wouldonly use the part of Cargo that handles building your code. As you write morecomplex Rust programs, you’ll add dependencies, and if you start a projectusing Cargo, adding dependencies will be much easier to do.

Because the vast majority of Rust projects use Cargo, the rest of this bookassumes that you’re using Cargo too. Cargo comes installed with Rust if youused the official installers discussed in the“Installation” section. If you installed Rustthrough some other means, check whether Cargo is installed by entering thefollowing into your terminal:

$ cargo --version

If you see a version number, you have it! If you see an error, such as command not found, look at the documentation for your method of installation todetermine how to install Cargo separately.

Creating a Project with Cargo

Let’s create a new project using Cargo and look at how it differs from ouroriginal “Hello, world!” project. Navigate back to your projects directory (orwherever you decided to store your code). Then, on any operating system, runthe following:

$ cargo new hello_cargo$ cd hello_cargo

The first command creates a new directory and project called hello_cargo.We’ve named our project hello_cargo, and Cargo creates its files in adirectory of the same name.

Go into the hello_cargo directory and list the files. You’ll see that Cargohas generated two files and one directory for us: a Cargo.toml file and asrc directory with a main.rs file inside.

(Video) Rust Programming Tutorial #2 - Hello World using Cargo

It has also initialized a new Git repository along with a .gitignore file.Git files won’t be generated if you run cargo new within an existing Gitrepository; you can override this behavior by using cargo new --vcs=git.

Note: Git is a common version control system. You can change cargo new touse a different version control system or no version control system by usingthe --vcs flag. Run cargo new --help to see the available options.

Open Cargo.toml in your text editor of choice. It should look similar to thecode in Listing 1-2.

Filename: Cargo.toml

[package]name = "hello_cargo"version = "0.1.0"edition = "2021"[dependencies]

Listing 1-2: Contents of Cargo.toml generated by cargo new

This file is in the TOML (Tom’s Obvious,Minimal Language) format, which is Cargo’s configuration format.

The first line, [package], is a section heading that indicates that thefollowing statements are configuring a package. As we add more information tothis file, we’ll add other sections.

(Video) Rust Programming Tutorial #3 - basic cargo commands | Hello, cargo!

The next three lines set the configuration information Cargo needs to compileyour program: the name, the version, and the edition of Rust to use. We’ll talkabout the edition key in Appendix E.

The last line, [dependencies], is the start of a section for you to list anyof your project’s dependencies. In Rust, packages of code are referred to ascrates. We won’t need any other crates for this project, but we will in thefirst project in Chapter 2, so we’ll use this dependencies section then.

Now open src/main.rs and take a look:

Filename: src/main.rs

fn main() { println!("Hello, world!");}

Cargo has generated a “Hello, world!” program for you, just like the one wewrote in Listing 1-1! So far, the differences between our project and theproject Cargo generated are that Cargo placed the code in the src directory,and we have a Cargo.toml configuration file in the top directory.

Cargo expects your source files to live inside the src directory. Thetop-level project directory is just for README files, license information,configuration files, and anything else not related to your code. Using Cargohelps you organize your projects. There’s a place for everything, andeverything is in its place.

If you started a project that doesn’t use Cargo, as we did with the “Hello,world!” project, you can convert it to a project that does use Cargo. Move theproject code into the src directory and create an appropriate Cargo.tomlfile.

(Video) Learning Rust: Hello World + Cargo

Building and Running a Cargo Project

Now let’s look at what’s different when we build and run the “Hello, world!”program with Cargo! From your hello_cargo directory, build your project byentering the following command:

$ cargo build Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo) Finished dev [unoptimized + debuginfo] target(s) in 2.85 secs

This command creates an executable file in target/debug/hello_cargo (ortarget\debug\hello_cargo.exe on Windows) rather than in your currentdirectory. Because the default build is a debug build, Cargo puts the binary ina directory named debug. You can run the executable with this command:

$ ./target/debug/hello_cargo # or .\target\debug\hello_cargo.exe on WindowsHello, world!

If all goes well, Hello, world! should print to the terminal. Running cargo build for the first time also causes Cargo to create a new file at the toplevel: Cargo.lock. This file keeps track of the exact versions ofdependencies in your project. This project doesn’t have dependencies, so thefile is a bit sparse. You won’t ever need to change this file manually; Cargomanages its contents for you.

We just built a project with cargo build and ran it with./target/debug/hello_cargo, but we can also use cargo run to compile thecode and then run the resulting executable all in one command:

$ cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs Running `target/debug/hello_cargo`Hello, world!

Using cargo run is more convenient than having to remember to run cargo build and then use the whole path to the binary, so most developers use cargo run.

Notice that this time we didn’t see output indicating that Cargo was compilinghello_cargo. Cargo figured out that the files hadn’t changed, so it didn’trebuild but just ran the binary. If you had modified your source code, Cargowould have rebuilt the project before running it, and you would have seen thisoutput:

$ cargo run Compiling hello_cargo v0.1.0 (file:///projects/hello_cargo) Finished dev [unoptimized + debuginfo] target(s) in 0.33 secs Running `target/debug/hello_cargo`Hello, world!

Cargo also provides a command called cargo check. This command quickly checksyour code to make sure it compiles but doesn’t produce an executable:

(Video) Rust Book 0002 - Hello Cargo! #rustlang

$ cargo check Checking hello_cargo v0.1.0 (file:///projects/hello_cargo) Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs

Why would you not want an executable? Often, cargo check is much faster thancargo build, because it skips the step of producing an executable. If you’recontinually checking your work while writing the code, using cargo check willspeed up the process of letting you know if your project is still compiling! Assuch, many Rustaceans run cargo check periodically as they write theirprogram to make sure it compiles. Then they run cargo build when they’reready to use the executable.

Let’s recap what we’ve learned so far about Cargo:

  • We can create a project using cargo new.
  • We can build a project using cargo build.
  • We can build and run a project in one step using cargo run.
  • We can build a project without producing a binary to check for errors usingcargo check.
  • Instead of saving the result of the build in the same directory as our code,Cargo stores it in the target/debug directory.

An additional advantage of using Cargo is that the commands are the same nomatter which operating system you’re working on. So, at this point, we’ll nolonger provide specific instructions for Linux and macOS versus Windows.

Building for Release

When your project is finally ready for release, you can use cargo build --release to compile it with optimizations. This command will create anexecutable in target/release instead of target/debug. The optimizationsmake your Rust code run faster, but turning them on lengthens the time it takesfor your program to compile. This is why there are two different profiles: onefor development, when you want to rebuild quickly and often, and another forbuilding the final program you’ll give to a user that won’t be rebuiltrepeatedly and that will run as fast as possible. If you’re benchmarking yourcode’s running time, be sure to run cargo build --release and benchmark withthe executable in target/release.

Cargo as Convention

With simple projects, Cargo doesn’t provide a lot of value over just usingrustc, but it will prove its worth as your programs become more intricate.Once programs grow to multiple files or need a dependency, it’s much easier tolet Cargo coordinate the build.

Even though the hello_cargo project is simple, it now uses much of the realtooling you’ll use in the rest of your Rust career. In fact, to work on anyexisting projects, you can use the following commands to check out the codeusing Git, change to that project’s directory, and build:

$ git clone example.org/someproject$ cd someproject$ cargo build

For more information about Cargo, check out its documentation.

(Video) Rust Programming - Hello World in Vim with Cargo, Rust Analyzer, Clippy

Summary

You’re already off to a great start on your Rust journey! In this chapter,you’ve learned how to:

  • Install the latest stable version of Rust using rustup
  • Update to a newer Rust version
  • Open locally installed documentation
  • Write and run a “Hello, world!” program using rustc directly
  • Create and run a new project using the conventions of Cargo

This is a great time to build a more substantial program to get used to readingand writing Rust code. So, in Chapter 2, we’ll build a guessing game program.If you would rather start by learning how common programming concepts work inRust, see Chapter 3 and then return to Chapter 2.

FAQs

Does NASA use rust language? ›

This project will provide Rust language support for NASA's core Flight System (cFS). The Rust language is designed to be memory-safe: it detects a wide range of programmer errors at compile-time while allowing low-level access to hardware and high performance.

Why is rust language so hard? ›

One of the problems why I found Rust hard to learn was that it looked similar to other imperative languages on one side, but introduced a lot of novel concepts. It has all these cycles, conditions, functions, like everyone else. But it also has the ownerships and traits and lifetimes.

Is Rust more difficult than C++? ›

Rust is far easier to learn than C++, but as the Recent Rust Developer Survey highlighted, very few people can currently code in Rust proficiently.

Is Rust easier than Python? ›

Rust is a more demanding language than Python. Its syntax is closer to that of low-level languages. That makes it probably not the best choice as the first technology to learn. The point has already been made that Python is not especially fast, but it could be said to be faster from a business perspective.

Does Tesla use Rust programming language? ›

Tesla uses python for defining and training their computer vision models, but then ports their python code to c++ in order to run it on the car. This is known as the two language problem. Rust is a systems language with a built in package manager, which puts it in a great position to be the perfect language.

Is Rust the safest language? ›

Through recent research on Rust, this new language was found to outperform well-established languages in terms of safety. Rust was found to be the safest language compared to C, C++, Java, Go, and Python.

Is it worth learning Rust in 2022? ›

RUST is an excellent language to learn in 2022. It is fast, safe, concurrent, and portable. It also has great tooling and a thriving community. If you are looking for a systems programming language, RUST is the perfect choice.

How much time will it take to learn Rust? ›

Learn with examples.

I would be able to do it in like 1 to 2 months. That much is enough to go through the staff once. Obviously, the aim is to start building projects in rust.

Should I learn C++ or Rust? ›

Here's the big hint – go with Rustlang. Sure, C++ has the lion's share of community support, and huge libraries, but Rust language is so much better in nearly every other way. Rust teaches you to code properly, and the tough love as a beginner is definitely appreciated by those further on in their careers.

Should I learn C++ or Rust 2022? ›

In a word: Yes! Learn Rust because it has things to teach. Learn C++ for what it has, too, and because it is the language work gets done in. They are much more similar than different.

Is Rust language beginner friendly? ›

I always argue that Rust is very beginner friendly because of how much babysitting the compiler does. It basically keeps your code around for a bit of a predebugging before letting it go off and do its thing.

Is Rust as powerful as C? ›

However, Rust programs also optimize quite well, sometimes better than C. While C is good for writing minimal code on byte-by-byte pointer-by-pointer level, Rust has powerful features for efficiently combining multiple functions or even whole libraries together.

Should I learn Rust or Java? ›

When it comes to Java, this programming language is significantly slower than Rust. Rust delivers faster startup times and smaller memory footprint on top of it. Java uses Garbage Collection for memory management, which decreases performance.

Is Rust as fast as C++? ›

In some benchmark over the internet (“Alioth Debian”) it shows Rust as being faster (by some operations per second) and in another (“TechEmpower”) that it is slower. But if you choose Rust, it is very likely that is both very fast, in “C++ like performance” and it is safe.

Should I learn Ruby or Rust? ›

You should learn Rust because it is a learning experience and forces you take a deeper look at your code, and that is something you will have to do when making any coding decision from what language to do a project in to how you want to store your data.

Does Facebook use Rust? ›

It joined the Rust Foundation in April 2021 as a platinum member with AWS, Google, Huawei, Microsoft and Mozilla. Facebook has used Rust since 2016, a year after version 1.0 of the language arrived.

What is Elon Musk's favorite programming language? ›

Elon Musk's iconic company, Tesla, operates on an operating system built on the Python programming language. Elon Musk continues to prefer it as his favourite programming language. Elon Musk is a brand in himself.

What language does Rust replace? ›

Rust is a possible replacement for C++ for many applications, with use mostly being driven by Rust's support for memory safety. Comparable to C++ in performance and platform support and controlled by an independent foundation, Rust is definitely a technology worth keeping an eye on.

What is fastest programming language? ›

C++ is one of the most efficient and fastest languages. It is widely used by competitive programmers for its execution speed and Standard Template Libraries(STL). Even though C++ is more popular, it suffers from vulnerabilities like buffer error. C++ executes at more or less the same speed as its predecessor C.

Is Rust harder to learn than Go? ›

The learning curve for Rust is pretty steep compared to Go. It's worth mentioning, however, that Go has a steeper learning curve than more dynamic languages such as Python and JavaScript.

Is Rust safer than C++? ›

Rust doesn't have any special feature that makes it fast and different from C and/or C++. It is much safer than C++ because of protection mechanisms it follows which, in principle, are also doable in C++ (using std::unique_ptr and std::shared_ptr ).

Is Rust in high demand? ›

Rust is unquestionably a popular language to use. It consistently ranks as the most loved language on the Stack Overflow Developer Survey and is easier to learn than C++. Greco confirms that Rust developers are in heavy demand in the crypto industry.

Is Rust developer in demand? ›

Rust has been steadily growing in popularity for the last number of years. In fact, according to this year's StackOverflow developer survey, Rust is the most beloved language by developers.

Should I learn Rust instead of C? ›

You'll always be making progress with C even if it's buggy. While learning C, I highly recommend that you dabble in Rust. Rust has introduced important concepts to programming that will not go away, and just does a lot of things really well, including C integration.

Is Rust the fastest language? ›

It's quite difficult to say which language is faster because it depends on case to case. But we can say that Rust is a competitor of C in terms of speed and it is faster than many other popular languages like Java and Python.

Is Rust a low level language? ›

Rust is a low-level programming language with direct access to hardware and memory, which makes it a great solution for embedded and bare-metal development.

Why Rust is the future? ›

Rust is the only 'safe' language which is also as fast as the native languages. That's it's key selling point. That's desirable for native developers since it's safer, and it's desirable for managed developers because it produces software that is faster and uses less memory.

Is Rust An OOP? ›

Many competing definitions describe what OOP is, and by some of these definitions Rust is object-oriented, but by others it is not. In this chapter, we'll explore certain characteristics that are commonly considered object-oriented and how those characteristics translate to idiomatic Rust.

Is Rust mature enough? ›

The Rust programming language has a lot of high-quality libraries. But the Rust ecosystem is not mature like Go, Python, or Java. In case you are unable to find something suitable, you will have to create it.

Will C++ be replaced by Rust? ›

Microsoft executive says it's time to retire the C and C++ programming languages and use Rust instead.

Does Rust replace C or C++? ›

Nothing is replacing C++ or C in general. There is just way too much code in those languages out there. There will still be reason to learn both languages in a hundred years time. Rust is an alternative choice for new projects.

Is Rust still popular 2022? ›

Rust was first released in early access in December 2013 and built a significant player base until its full release in February 2018. In August 2022, Rust had more than 134.92 thousand peak concurrent players on Steam.

Should I learn Python or Rust first? ›

What should I do/ what do you suggest? Rust is a great language, but personally I would recommend going for Python. In my opinion, learning your first language isn't just about learning the syntax of that specific language. Instead, it's also about learning how to program, and how to solve problems programmatically.

What's the hardest coding language? ›

C++ C++ is considered to be one of the most powerful, fastest, and toughest programming languages.

Can I directly learn Rust? ›

Interactive Learning

rustlings has small exercises to get you used to reading and writing Rust code. You can use this along with The Rust Programming Language. When you save the file, it will automatically check the answer and gives you feedback.

Can Rust do everything C++ can? ›

But yes, C++ can do everything Rust can, and vice versa. They are complete programming languages in that respect.

Is Rust used at Google? ›

Google's KataOS is written "almost entirely in Rust", the programming language that's been adopted by the Android Open Source Project and the Linux kernel project.

Is more RAM better for Rust? ›

RAM memory is the most important resource, and according to the official Rust Wiki, you need to have at least 4GB of RAM memory and 8GB of RAM for the best available performance. Generally, the more RAM you have, the better it is.

Which programming language is used by NASA? ›

HAL/S (High-order Assembly Language/Shuttle) is a real-time aerospace programming language compiler and cross-compiler for avionics applications used by NASA and associated agencies (JPL, etc.).

What programming language is NASA using? ›

So what is NASA using? MATLAB – mainly for engineering analysis. Python – for analysis, data science, GUIs, and open-source projects. Other languages – such as Fortran, Node.

What language is NASA written in? ›

Hello Abdul, The programming language used by NASA is HAL/S ( high order assembly language / shuttle). It is a realtime aerospace programming language compiler and cross compiler used for aviation technology. For ground operations c, c++, java and python are used.

Which language is spoken in NASA? ›

Language On The ISS

Astronauts need to speak Russian at an intermediate-high level for the purposes of getting there and back, because all the procedures and labels are written in Russian on the Soyuz.

How does Netflix use Python? ›

As per developers at Netflix, Python is used through the "full content lifecycle,” from security tools to its recommendation algorithms, and its proprietary content distribution network (CDN) Open Connect. Most of the network devices at Netflix are managed by Python-based applications.

What programming language is SpaceX? ›

In SpaceX, both C and C++ are used for flight software. SpaceX's Falcon 9 rocket used dual-core x86 processors, and the flight software that runs on each of these processors is written in either C or C++. C++ is one of the most powerful, fastest, and heavily used programming languages.

Does NASA Need coders? ›

Does NASA need coders? Yes, they do, but they rarely refer to them as coders. Most jobs posted by NASA or subcontractors are for software engineers who write code for NASA. Because most of NASA's priorities involve computers, many job openings are available for those who know how to code and program.

Which programming language is best for coding? ›

What coding and programming language should i learn? JavaScript and Python, two of the most popular languages in the startup industry, are in high demand. Most startups use Python-based backend frameworks such as Django (Python), Flask (Python), and NodeJS (JavaScript).

What is the oldest programming language still in use? ›

The oldest programming language is Fortran, which was first commercially released in 1957. A group of programmers at IBM, under the direction of John Backus, first created the programming language.

Does NASA use R or Python? ›

Internal sources within the critical project added that: “Python allows us to tackle the complexity of programs like the WAS without getting bogged down in the language”. Moreover, another indication NASA utilizes Python for their projects can be found from their mega 400 open-source projects that they publicly opened.

Does Facebook use Python? ›

Facebook loves Python because the ease of using its libraries means that production engineers don't have to write or maintain as much code, freeing them to focus on getting improvements live. Also, it ensures that Facebook's infrastructure scales efficiently.

Does NASA use MATLAB or Python? ›

NASA has used many different programming languages ​​throughout its history. Even today, different computer programs are used for different applications. For example, HAL / S has been used for many NASA spacecraft, including the Space Shuttle. Today, ground computers use languages ​​such as C ++, Python and MATLAB.

Which human language is best for computer? ›

It is important to understand that humans and computers understand different languages. “Natural Languages” are the languages understood by humans like English, Hindi and even Sanskrit. On the other hand, “Machine/Artificial languages” include Lisp or C or Prolog.

Is Sanskrit dead language? ›

The Sanskrit language scholar Moriz Winternitz states, Sanskrit was never a dead language and it is still alive though its prevalence is lesser than ancient and medieval times. Sanskrit remains an integral part of Hindu journals, festivals, Ramlila plays, drama, rituals and the rites-of-passage.

Which is the most scientific language? ›

Sanskrit was the language of our philosophers, our scientists, our mathematicians, our poets and playwrights, our grammarians, our jurists, etc.

Videos

1. Rust Programming Language #2 | Hello World Using Cargo | Urdu/Hindi
(masTech Developer)
2. Rust-Lang Introduction - Hello, World! - Cargo - About Rust
(Tuxmascot)
3. Rust Cargo.toml
(Doug Milford)
4. Hello, Cargo | Understanding Cargo Statements | Rust Programming Language [ Part 2 ]
(Sameer Negi)
5. Getting started with Rust programming language 🦀 in 2020: 3. Cargo crash course
(creativcoder)
6. The Rust Programming Language - Introducing the Cargo Package Manager!- Video 03
(Knowledge Hub)
Top Articles
Latest Posts
Article information

Author: Edwin Metz

Last Updated: 01/09/2023

Views: 6084

Rating: 4.8 / 5 (78 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Edwin Metz

Birthday: 1997-04-16

Address: 51593 Leanne Light, Kuphalmouth, DE 50012-5183

Phone: +639107620957

Job: Corporate Banking Technician

Hobby: Reading, scrapbook, role-playing games, Fishing, Fishing, Scuba diving, Beekeeping

Introduction: My name is Edwin Metz, I am a fair, energetic, helpful, brave, outstanding, nice, helpful person who loves writing and wants to share my knowledge and understanding with you.