Compile and run a Rust program using Cargo

Pascal Precht
InstructorPascal Precht
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 years ago

In this lesson we'll learn how to use the cargo run command to compile and run a Rust program.

Instructor: [00:00] We can compile a Rust project using Cargo and its built commands. This will create a target directory in which we can find the executable of our program. From here, we can again run our program on the command line.

[00:20] A more convenient way to compile and run our Rust program is to use Cargo's run command. This one will compile and execute the program in one go. Cargo also comes with a clean command to remove the generated target. Once executed, we can see that the target directory has been removed from the project.

J. Matthew
J. Matthew
~ 4 years ago

The benefits of cargo run seem obvious, but I'm curious what is the difference between using cargo build from this lesson and rustc main.rs from lesson 2? I assume the latter is what the former is using under the hood but that it also generates other material useful for debugging and such?

J. Matthew
J. Matthew
~ 4 years ago

Also worth noting: I tried out the official "Rust (rls)" extension for VS Code, and discovered that it also creates a folder under target, called rls, which is adjacent to the debug subfolder created by cargo build and cargo run. This is significant because it turns out that cargo clean doesn't delete the target folder indiscriminately, but rather the aforementioned debug subfolder, and the parent target only if there's nothing else in there. So, if you're using that extension, its content is preserved while the build is still deleted—very nice!

Pascal Precht
Pascal Prechtinstructor
~ 4 years ago

I assume the latter is what the former is using under the hood but that it also generates other material useful for debugging and such?

That is correct. cargo build lets you specify what target environment you want to compile to (e.g. development, production etc).

So, if you're using that extension, its content is preserved while the build is still deleted—very nice!

Ah, good to know! Thanks for bringing this up. I don't use VS Code so sorry this brought up confusion.

Markdown supported.
Become a member to join the discussionEnroll Today