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!

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

相关推荐
Kapaseker5 分钟前
同样 4 行代码,C++ 编译通过,Rust 为什么直接拒绝?
rust
DongQiShanRen5 小时前
六根硬件映射(中):双站校验、生克闭环与驱动接口
数据库·人工智能·算法·rust·哈希算法·集成学习
Amos_Web5 小时前
Rspack 源码解析(二十五):CssParserAndGenerator 如何把 CSS 变成可 Tree Shaking 的模块
前端·rust·前端框架
Kainy5 小时前
Rust重写Photoshop开源项目PhotoCraft:无头命令行修图与AI Agent自动化实战
人工智能·rust·photoshop
I'm Jie5 小时前
Rhost v2.0.0 版本发布!!!不止 SSH 终端,内置 AI Agent 支持自然语言操作远程服务器
运维·服务器·rust·开源·ssh·tauri·finalshell
青川Lapis20 小时前
RUST:错误处理 thiserror 详解
rust
Source.Liu1 天前
【A11】拥有者模式平台架构笔记
windows·笔记·架构·rust
sayang_shao1 天前
用 Rust 开发 STM32H743:从零搭建一个能烧录、能看日志的项目
stm32·单片机·rust
qq_406981031 天前
大白话rust系列02原始数据类型
rust
遇码1 天前
macOS 触摸板捏合在 GPUI 里无响应:vendor 打补丁,把手势合成为 cmd+滚轮事件
rust·图形渲染·策略模式·桌面应用·gpui