tencent cloud

TencentOS Server

Rust Development Guide

ダウンロード
フォーカスモード
フォントサイズ
最終更新日: 2026-10-19 17:22:51
AI翻訳

Introduction to Rust

Rust is an efficient and reliable general-purpose high-level language, with a focus on safety, concurrency, and practicality. Cargo is the build system and package manager for Rust.

Installing Rust

Using dnf

To install the Rust-toolset software package on TencentOS Server, run the following command:
sudo dnf install rust-toolset
After installation, run the following command to check whether Rust is installed correctly. The current installed version, hash value, and commit date are displayed.
rustc -V
cargo -V

Using rustup

In addition to the dnf installation method, you can also install Rust using rustup. The basic installation commands are as follows:
sudo dnf install rustup
rustup toolchain install stable
After successful installation, you can also run cargo -V to verify the installation result. The version number, commit hash, and commit date of the latest stable release are displayed.
If the following error occurs during installation, switch from the root user to an ordinary user and then run rustup toolchain install stable again:
rustup toolchain install stable
info: syncing channel updates for 'stable-x86_64-unknown-linux-gnu'

stable-x86_64-unknown-linux-gnu unchanged - rustc 1.69.0 (84c898d65 2023-04-16)

error: rustup is not installed at '/root/.cargo'

Using Rust

Cargo is the build tool and dependency manager for the Rust compiler. You can use it to declare dependencies with specific version constraints, resolve the complete dependency graph, download packages, and build and test entire Rust projects. Rust developers commonly use Cargo to manage Rust projects and obtain the libraries they depend on.

Creating Projects

Project Types

Cargo can build a Rust project with one click by running the cargo new command, for example, creating a classic project:
cargo new hello_world --bin # In earlier versions of cargo, you must specify --bin to create a binary project.
cargo new hello_world # Same as above.
Create a new Rust library:
cargo new --lib hello_lib
Note:
Rust projects are mainly divided into two types: bin and lib. The former is a runnable project, and the latter is a dependency library project.
In earlier versions of cargo, you had to add the --bin parameter when creating a project. The cargo version provided here creates a bin project by default, so you do not need to explicitly specify the --bin parameter.

Project Structure

After the project is created, view the project structure:
tree
.
├── Cargo.toml
└── src
└── main.rs
At this point, the project directory structure is relatively simple. In most cases, it may contain other directory structures, which are explained as follows:
Cargo.toml: a project description file or manifest specific to Cargo, which contains all the metadata required for Cargo to compile the project.
Cargo.lock: the Cargo.lock file is a detailed list of project dependencies generated by the Cargo tool based on the toml file of the same project, and generally does not need to be modified.
src: the directory where source code is stored.
src/main.rs: the main executable file. When editing project code, modify main.rs and add new source files to the src subdirectory.
benches: the directory for storing benchmarks.
examples: the directory for storing sample code.
tests: the directory for storing integration test code.
The format of the Cargo.toml file is interpreted as follows:
[package]: defines the metadata of the project (package).
name: the project name.
version: the project version.
authors: the project authors.
edition: the major Rust version currently in use.
rust-version: the minimum required Rust version.
description: the project description.
documentation: the documentation.
readme: the README file.
homepage: the homepage.
repository: the source code repository.
license: the open source license.
License-file: the License file.
keywords: the project keywords.
categories: the project categories.
workspace: the workspace.
build: the script build path.
links: the name of the local link library.
exclude: exclude files during publishing.
include: include files during publishing.
publish: prevents the project from being published.
metadata: additional configuration information for external tools.
default-run: the default executable file (binary) used by [cargo run].
autobins: disables automatic discovery of executable files.
autoexamples: disables automatic discovery of example files.
autotests: disables automatic discovery of test files.
autobenches: disables automatic discovery of bench files.
resolver: sets the dependency resolver.

Running Projects

There are two ways to run your Rust project: the first is to compile it manually and then execute it, and the second is to do it all in one step.

Step-by-Step Execution

Compile manually using the Cargo build tool:
cargo build
You can then see that a target folder has been generated in the project, and the corresponding executable file has been generated in the target/debug directory. You can run it manually.
# View the file type
file target/debug/hello_world
target/debug/hello_world: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=c87cf5694fab5ba052821001f3d9c31070543413, for GNU/Linux 3.2.0, with debug_info, not stripped
# Run Manually
./target/debug/hello_world

Single-Step Execution

For developers using languages such as C/C++, the compile-then-execute workflow may be all too familiar. However, for Rust developers, Cargo also provides a one-command run option:
cargo run
Compiling hello_world v0.1.0 (/root/test/hello_world)
Finished dev [unoptimized + debuginfo] target(s) in 0.25s
Running `target/debug/hello_world`
cargo run first compiles the project and then runs it, so it is effectively equivalent to running two separate commands, which simplifies the workflow for users.

debug/release Modes

Whether you run the steps manually or use the one-command option, after execution completes, you can see that a debug directory has been created under target, which means the debug mode is run by default.
tree -L 2
.
├── Cargo.lock
├── Cargo.toml
├── src
│ └── main.rs
└── target
├── CACHEDIR.TAG
└── debug # debug mode
In debug mode, code compiles quickly, allowing developers to build smoothly. However, this also means slower runtime performance, which can negatively impact release. Therefore, you can explicitly specify the release mode when publishing:
cargo run --release
cargo build --release
Similarly, a corresponding release directory will be created under target:
tree -L 2
.
├── Cargo.lock
├── Cargo.toml
├── src
│ └── main.rs
└── target
├── CACHEDIR.TAG
├── debug
└── release # release mode

Checking Projects

When a Rust project becomes bloated, using cargo run and cargo build to verify code correctness can be time-consuming. In this case, you can use cargo check to quickly compile the code:
cargo check
Finished dev [unoptimized + debuginfo] target(s) in 0.02s
Additionally, you can run tests for the Rust project. If the project contains many tests, you can also specify running a single test or filtering some tests. Note that the return type must be () or Result<(), E> where E: Error.
cargo test # debug mode
cargo test --release # release mode

Project Documentation

Cargo also supports extracting comments from source code to generate documentation. However, note that:
Extract doc comments only for public functions, variables, and members;
Mark the extracted comments with three slashes ///;
cargo doc --no-deps

Introduction to Rust Tool rustfmt

rustfmt is a tool for formatting Rust code that helps developers ensure code cleanliness, consistency, and readability. You can use rustfmt to automatically format Rust code according to the community-recommended code style, providing consistent code standards. rustfmt can be used either independently or together with Cargo.
Before using rustfmt, ensure that rustfmt is installed. If it is not installed yet, you can easily install it by running the following command:
dnf install rustfmt
After successfully installing rustfmt, you can use it as follows:

Using rustfmt Standalone

After you run the rustfmt command, the program formats the specified Rust source file according to the default configuration specifications. By default, rustfmt outputs the formatted content directly to the terminal.
rustfmt src/test.rs
To format a file in place, if you want rustfmt to directly modify the source file by formatting it in place, you can use the --emit flag:
rustfmt --emit files src/test.rs

Using with Cargo

rustfmt xx.rs can format a specified file, while the cargo fmt command automatically applies rustfmt formatting rules to format all .rs files in the project.
cargo fmt
To customize formatting rules, you need to create a file named rustfmt.toml in the project root directory or any parent directory. In this file, you can add key-value pair configurations without quotation marks, for example:
max_width = 100
reorder_imports = true
After you create the rustfmt.toml file, rustfmt automatically applies the configuration options in it to format your code.

FAQs

Cargo.toml Validation

After Cargo.toml is modified, validation fails.
error: the listed checksum of `/builddir/build/BUILD/gnome-tour-43.0/vendor/glib-macros/Cargo.toml` has changed:
expected: d6e10d3ec19f19b5a32cdcd159567ede9fa1e59ac13f446f0a1e40f99e7e6c1b
actual: ea00aa6587f4f1793c296fd4a18c9989239e13df703c9254906b1c757714d440

directory sources are not intended to be edited, if modifications are required then it is recommended that `[patch]` is used with a forked copy of the source
The error above is caused by modifying the Cargo.toml file without updating the checksum file .cargo-checksum.json accordingly. To resolve it, find the Cargo.toml entry in the json file and change it to the actual value. The same applies to checksum errors for other files.
# Change "Cargo.toml" to "d6e10d3ec19f19b5a32cdcd159567ede9fa1e59ac13f446f0a1e40f99e7e6c1b"
# Change it to "Cargo.toml":"ea00aa6587f4f1793c296fd4a18c9989239e13df703c9254906b1c757714d440"

Cargo.lock Specified Version Mismatch

Cargo.toml describes the version requirements, while Cargo.lock is automatically generated based on the build environment.
For example, by viewing the Cargo.toml file in gnome-tour-43.0, you can see that the build requires gtk3 version 0.4.x.
[dependencies]
gtk = { package = "gtk3", version = "0.4", features= ["v4_2"]}
log = "0.4"
gettext-rs = { version = "0.7", features = ["gettext-system"] }
adw = {package = "libadwaita", version = "0.1"}
pretty_env_logger = "0.4"
regex = "1.5"
When Cargo.lock is first generated, the build source provides gtk3 version 0.4.8, so Cargo.lock locks the version to 0.4.8. When it is used later, the source provides gtk3 upgraded to 0.4.9, and the build fails with an error:
error: failed to select a version for the requirement `gtk3 = "^0.4"` (locked to 0.4.8)
candidate versions found which didn't match: 0.4.9
By referring to Cargo.toml in gnome-tour-43.0, you can see that gtk3-0.4.9 already meets the build requirements. Therefore, this error is not necessary, and you need to update the Cargo.lock file to eliminate it. Since Cargo.lock is automatically generated from Cargo.toml, manual modification is generally not recommended. Instead, you should trigger the update by adjusting Cargo.toml.
If the vendor directory of gnome-tour-43.0 contains a gtk3 folder, update version in vendor/gtk3/Cargo.toml to 0.4.9.
[package]
edition = "2021"
rust-version = "1.56"
name = "gtk3"
version = "0.4.9"
Then run cargo update in the gnome-tour-43.0 directory to automatically update the Cargo.lock file:
cargo update
Updating gtk3 v0.4.8 -> v0.4.9
After the update is complete, you can compile normally.

Appendix

For more usage methods, see:

ヘルプとサポート

この記事はお役に立ちましたか?

フィードバック