Table of contents
1.2 Building applications with Rust
Windows Subsystem for Linux (WSL)
Cargo: A build tool and package manager for Rust
3. Configure the PATH environment variable
4. Development tools support Rust.
5. Write your first Rust program
6. Use Cargo to create a project
Build and run the Cargo project
1 Introduction
Rust is a language that empowers everyone to build reliable and efficient software.
1.1 Why Choose Rust
high performance
Rust is incredibly fast and memory efficient. Since there is no runtime and garbage collection, it is capable of performing services with particularly high performance requirements, can run on embedded devices, and can be easily integrated with other languages.
reliability
Rust's rich type system and ownership model guarantee memory safety and thread safety, allowing you to eliminate a variety of errors at compile time.
productive forces
Rust has excellent documentation, a friendly compiler and clear error messages. It also integrates first-class tools - package managers and build tools, multi-editor support for intelligent auto-completion and type checking, and automatic formatting. Code and so on.
1.2 Building applications with Rust
Command Line
Quickly implement command-line tools using Rust's powerful ecosystem. Rust helps you maintain and distribute your applications with confidence.
WebAssembly
Use Rust to enhance your JavaScript modules piece by piece. Publish to npm, use webpack to package, and you will feel the amazing speed increase.
network
Predictable performance, minimal resource usage, and rock-solid reliability. Rust is extremely suitable for web services.
Embedded
Targeting resource-hungry devices? Need low-level control without losing the convenience of upper-level abstraction? Rust guarantees your satisfaction!
2. Install Rust
The first step is to install Rust. We will download Rust through rustup
, which is a tool for managing Rust versions and related
Tools command line tool. An Internet connection is required for downloading.
On Windows, go to https://www.rust-lang.org/install.html and follow the instructions to install Rust. At some point in the installation process, you will receive a message explaining why you need to install the MSVC build tools for Visual Studio 2013 or newer.
To get the build tools, you need to install Visual Studio 2022. When asked what workload needs to be installed, make sure you check the following:
- "Desktop Development with C++"
- Windows 10 (or 11) SDK
- English language pack, and other language packs you need
Download and install at the following page address:Install Rust - Rust programming language
Windows Subsystem for Linux (WSL)
If you are a Windows Subsystem for Linux (WSL) user, to install Rust, run the following commands in a terminal and follow the on-screen instructions to complete.
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
Check that Rust is up to date
Rust is upgraded very frequently. If it's been a while since you installed Rustup, it's likely that your version of Rust is out of date. Run rustup update
to get the latest version of Rust.
rustup update
Check the current Rust version:
rustc --version
Uninstall the Rust version:
rustup self uninstall
Cargo: A build tool and package manager for Rust
When you install Rustup, you also install the latest stable version of the Rust build tools and package manager, Cargo. Cargo can do many things:
cargo build
Can build the projectcargo run
Can run the projectcargo test
Projects can be testedcargo doc
Can build documentation for the projectcargo publish
can publish libraries to crates.io.
To check if you have Rust and Cargo installed, run:
cargo --version
3. Configure the PATH environment variable
In the Rust development environment, all tools are installed into the ~/.cargo/bin directory, where you can find the Rust tool chain, including rustc, cargo, and rustup.
Therefore, Rust developers are accustomed to including this directory in their PATH environment variable. During installation, rustup will try to configure PATH. Due to differences between platforms, command shells, and errors in rustup, modifications to PATH may not take effect until the console is restarted or the user logs off, or may not succeed at all.
If running rustc --version on the console fails after installation, this is the most likely cause.
4. Development tools support Rust.
VSCode
You can find and install the rust-analyzer extension from VS Code via the Extensions view (Ctrl+Shift+X) and search for 'rust-analyzer'. Select the corresponding version to install.
The main functions are:
- Import inserted code completion
- Go to Definition, Implementation, Type Definition
- Find all references, workspace symbol search, symbol rename
- Types and documentation on hover
- Embedded hints for type and parameter names
- Semantic syntax highlighting
- Lots of assistance (code manipulation)
- Apply suggestions from errors
- ...and more, check outmanualview all
5. Write your first Rust program
Next, create a new source file named main.rs. Rust source files always end with the .rs extension. If the file name contains multiple words, then naming convention should use underscores to separate the words. For example, name it hello_world.rs
fn main() {
println!("Hello, world!");
}
Then start compiling and running:
rustc main.rs
After compilation, there will be 2 new files, and then run the compiled executable file (main.exe).
./main.exe
Analyze this Rust program
fn main() {
}
These lines define a function named main
. The main
function is a special kind of function: it is always the first code to run in an executable Rust program. The first line of code declares a function called main
, which has no parameters and no return value. If there are parameters, their names should appear in parentheses ()
.
The function body is wrapped in {}
. Rust requires all function bodies to be wrapped in curly braces. Generally speaking, it is good coding style to place the opening curly brace on the same line as the function declaration and separate them with spaces.
There is the following code in the main
function:
fn main() {
println!("Hello, world!");
}
This line of code does everything this simple program does: prints text on the screen. There are four important details to note here. First, Rust's indentation style uses 4 spaces instead of 1 tab.
Second,println!
calls a Rust macro. If you are calling a function, you should enter println
(without !
). We will discuss macros in detail in Chapter 19. For now just remember that when you see the symbol !
it means that a macro is being called rather than a normal function, and macros don't always follow the same rules as functions.
Third, "Hello, world!"
is a string. We pass this string as a parameter to println!
and the string will be printed to the screen.
Fourth, the line ends with a semicolon (;
), which represents the end of one expression and the beginning of the next. Most lines of Rust code end with a semicolon.
6. Use Cargo to create a project
Cargo is a build system and package manager for Rust. Most Rustaceans use Cargo to manage their Rust projects because it handles many tasks for you, such as building your code, downloading dependent libraries, and compiling those libraries.
First, you can check whether cargo has been installed locally, as shown below:
cargo --version
Then, start creating the project:
cargo new hello_cargo
Enter the hello_cargo directory and list the files. You will see that Cargo generated four files and a directory: a Cargo.toml file, and a src< /span>main.rs directory, and src directory file, a .git folder, and a .gitignore file.
Cargo.toml file This is the format of the Cargo configuration file. The file contents are as follows:
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
Build and run the Cargo project
We can build it with the following command as shown below:
cargo build
This command will generate the target directory and create an executable file target/debug/hello_cargo (on Windows target\debug\hello_cargo.exe)
We can execute the executable file in the corresponding path, as shown below:
We just built the project using cargo build
and ran the program using ./target/debug/hello_cargo
, you can also use cargo run
in a Compile and run the generated executable file at the same time in the command:
cargo run
Cargo also provides a command called cargo check
. This command quickly checks the code to make sure it compiles, but does not produce an executable file:
Why don't you need an executable file? Usually cargo check
is much faster than cargo build
because it omits the step of generating an executable file. If you continue to check when writing code, cargo check
can let you quickly know whether the current code can compile normally! For this reason many Rustaceans write code that regularly runs cargo check
to make sure they compile. Run cargo build
only when you are ready to use the executable.
release build
When the project is finally ready for release, you can use cargo build --release
to optimize the compiled project. This will generate the target under target/release instead of target/debug executable file. These optimizations can make Rust code run faster, but enabling these optimizations also takes longer to compile. That's why there are two different configurations: one for development, where you need to rebuild quickly and often, and one for building final applications for users, who don't rebuild often and want the program to run as fast as possible. good. If you are testing the running time of your code, make sure to run cargo build --release
and use the executable under target/release test.
cargo build --release
Then run the executable file in the release directory, as shown in the figure below: