Cargo

Cargo

cargo是rust的构建系统和包管理工具,在安装rust的时候就一并安装了cargo。

shell 复制代码
> cargo --version
cargo 1.78.0 (54d8815d0 2024-03-26)

使用cargo创建项目

shell 复制代码
cargo new hello_cargo

会生成

  • src 源码目录
  • Cargo.toml
  • Cargo.lock
  • .gitignore 仓库文件

Cargo.toml

Tom's Obvious, Minimal Language,是cargo的项目配置。

toml 复制代码
[package] # 包配置
name = "hello_cargo"                        # 包名
version = "0.1.0"                           # 包版本
authors = ["xiaolipro <2357729423@qq.com>"] # 作者
edition = "2021"                            # rust版本

[dependencies] # 第三方依赖项

target

build后下载的依赖库、生成的可执行文件都在这个目录

使用cargo clean命令可以删除

shell 复制代码
> cargo clean
     Removed 224 files, 16.1MiB total

编译

cargo check

cargo check命令用于代码检查,确保编译能够通过,但不会生成可执行文件。

因此cargo check比cargo build快得多,在编码阶段就可以频繁的使用,来检查代码、提高效率。

shell 复制代码
> cargo check     
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.02s

cargo build

cargo build命令就是在cargo check检查代码的基础上,多生成了可执行文件。

发布时,cargo build往往需要带上release参数,生成优化后的代码。

shell 复制代码
> cargo build --release
   Compiling hello_cargo v0.1.0 (C:\Antinew\我的\2024\rust\hello_cargo)
    Finished `release` profile [optimized] target(s) in 0.32s

可以看到,release模式,需要重新编译才能生成optimized代码,与之对应的,就是更长的等待时间

运行

cargo run

cargo run命令包含编译和执行。

shell 复制代码
> cargo run
   Compiling hello_cargo v0.1.0 (C:\Antinew\我的\2024\rust\hello_cargo)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.46s
     Running `target\debug\hello_cargo.exe`
Hello, world!

如果已经编译过了,且源码没有发生改变,那么会直接运行可执行文件。

相关推荐
AI首席情报员_阿布13 小时前
Numa:用 Rust 从零造一个 DNS 解析器,顺手解决了开发者最头疼的几件事
人工智能·rust·dns
Rust研习社13 小时前
Rust 多线程从入门到实战
开发语言·后端·rust
无巧不成书021815 小时前
Rust开发环境完全指南:Windows/Linux双平台配置与实战
linux·windows·rust·gnu·msvc·mingw-w64安装·镜像配置
Source.Liu15 小时前
【Tauri】Tauri 框架介绍
rust·tauri
Rust研习社15 小时前
深入浅出 Rust 泛型:从入门到实战
开发语言·后端·算法·rust
fox_lht17 小时前
8.3.使用if let和let else实现简明的程序流控制
开发语言·后端·算法·rust
Mr -老鬼1 天前
Salvo Web框架专属AI智能体 - 让Rust开发效率翻倍
人工智能·后端·rust·智能体·salvo
本地化文档1 天前
rustup-book-l10n
rust·github·gitcode
代码羊羊1 天前
Rust泛型编程:从零成本抽象到极致性能
开发语言·windows·rust
misL NITL1 天前
数据库操作与数据管理——Rust 与 SQLite 的集成
数据库·rust·sqlite