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 <[email protected]>"] # 作者
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!

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

相关推荐
景天科技苑1 小时前
【Rust结构体】Rust结构体详解:从基础到高级应用
开发语言·后端·rust·结构体·关联函数·rust结构体·结构体方法
苏近之1 小时前
说明白 Rust 中的泛型: 泛型是一种多态
设计模式·rust
bruce541103 小时前
【智能指针】一文带你入门Rust 智能指针
rust
用户0996918801818 小时前
Rust JSON 数据处理:take 与 clone 的权衡
rust
bruce5411020 小时前
Rust学习之实现命令行小工具minigrep(二)
rust
广龙宇1 天前
【一起学Rust】使用Thunk工具链实现Rust应用对Windows XP/7的兼容性适配实战
开发语言·windows·rust
UestcXiye1 天前
Rust 学习笔记:安装 Rust
rust
CHQIUU1 天前
【Rust 精进之路之第2篇-初体验】安装、配置与 Hello Cargo:踏出 Rust 开发第一步
rust
苏近之1 天前
Rust 重构 Rust:枚举和模式匹配
rust·代码规范
liyu111 天前
Tauri 2.x 版本 辅助性 Accessory App 如何实现单例模式 (MAC & Windows)
rust