Hello Cargo

Hello Cargo

  • Cargo 是 Rust 的构建系统和包管理工具
  • Rust 安装时会默认安装 Cargo
    • cargo --version
$ cargo --version
cargo 1.78.0 (54d8815d0 2024-03-26)

使用 Cargo 创建项目

  • cargo new hello-cargo

    • 上述命令会创建新的目录 hello-cargo
    • Cargo.toml 配置文件
    • src 目录
      • main.rs
    • .gitignore 默认初始化一个新的 git 仓库
  • /Cargo.toml

    • [package] 区域标题,配置包
      • name 项目名称
      • version 项目版本
      • edition 使用Rust版本
    • [dependencies] 依赖项
    • rust 中,代码包称之为 crate
[package]
name = "hello-cargo"
version = "0.1.0"
edition = "2021"

[dependencies]
  • /src/main.rs
    • 源代码都应该放置到 src 下;
    • 顶层目录可以放 Readme 许可信息、配置信息等;

使用 Cargo Build 构建项目

$ cargo build
  Compiling hello-cargo v0.1.0 (/Users/stellonde/Code/rust/rust-new-knowledge/code/01-hello-world/hello-cargo)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.26s

会生成 Cargo.lock 文件

# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3

[[package]]
name = "hello-cargo"
version = "0.1.0"

会生成 target 目录

使用 Cargo Run 构建并运行项目

$ cargo run
   Compiling hello-cargo v0.1.0 (/Users/stellonde/Code/rust/rust-new-knowledge/code/01-hello-world/hello-cargo)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.07s
     Running `target/debug/hello-cargo`
Hello, world!

# 如果多次执行,源代码没有变化,则直接省去 compile 过程
$ cargo run
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/hello-cargo`
Hello, world!

使用 Cargo Check 快速检查代码

  • Cargo Check 检查代码,确保可以编译通过,但是不产生任何可执行文件
    • 用于编写代码的时候快速反复的检查代码,相比 cargo build ,效率高的多
$ cargo check
    Checking hello-cargo v0.1.0 (/Users/stellonde/Code/rust/rust-new-knowledge/code/01-hello-world/hello-cargo)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.02s

使用 Cargo Build 发布构建

  • 编译的时候会进行优化
    • 代码运行更快,但是编译时间更长
  • 编译后的可执行文件位置
    • target/release 下
    • target/debug 是开发过程中生成的位置
$ cargo build --release
  Compiling hello-cargo v0.1.0 (/Users/stellonde/Code/rust/rust-new-knowledge/code/01-hello-world/hello-cargo)
    Finished `release` profile [optimized] target(s) in 0.10s
明天我们吃什么 悲哀藏在现实中 Tacks
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!