Rust环境配置

1. 安装rust

根据官网提示和自己的系统选择安装方式, mac和linux可以直接使用命令行

1.1 更新rust

  • 更新rust: rustup update
  • 卸载: rustup self uninstall
  • 添加组件: rustup component add rustfmt
  • 查看版本: rustup --version

1.2 Rust的两种版本 Stable与Nightly

  • stable: 最稳定和可靠的版本

  • nightly: 每天构建的最新版本

  • 安装: rustup install stable/nightly

  • 切换: rustup default stable/nightly

2. 编译器与包管理工具

2.1. Rust编译语言的编译器rustc

  • 查看版本: rustc --version
  • 编译生成二进制文件: rustc -o output_filename filename.rs
  • 编译生成库文件: rustc --crate-type lib filename.rs

2.2 Rust的包管理工具Cargo

  • 隐式的使用rustc进行编译
  • 命令
    • 创建:
      • rust项目: cargo new project_name
      • rust库项目: cargo new --lib project_name
    • 构建项目(生成二进制可执行文件或库文件):
      • cargo build
      • cargo build --release 为生成优化的可执行文件,常用于生产环境
    • 检测: cargo check
    • 运行/测试: cargo run/cargo test

2.3 项目结构

库:

  • project_name/

可以执行二进制:

  • project_name

Cargo.toml文件

  • package:

    • 设置项目名
    • 版本等等
  • dependencies:

    • 设置依赖
    • build-dependencies\]列出了在构建项目时需要的依赖项

3. 获取Rust库

3.1 方式一:

  • 修改Cargo.toml文件

以random库为例:

  1. 在Cargo.toml文件下添加依赖
rust 复制代码
random = "=0.14.0"
  1. 使用提供的example测试
rust 复制代码
use random::Source;

fn main() {
    let mut source = random::default(42);
    println!("Scalar: {:?}", source.read::<f64>());
    println!("Vector: {:?}", source.iter().take(2).collect::<Vec<f64>>());
}

3.2 方式二: cargo-edit

  1. 安装: cargo install cargo-edit
  2. 添加库
    • cargo add [dependency_name]
    • 安装指定版本: cargo add [dependency_name]@123
    • 添加开发时用的依赖库: cargo add --dev dev_dependency_name
    • 添加构建时用的依赖库: cargo add --build build_dependency_name
  3. 删除库: cargo rm [dependency_name]

3.3 设置国内源

推荐: rsproxy.cn

设置 crates.io 镜像, 修改配置 ~/.cargo/config,已支持git协议和sparse协议,>=1.68 版本建议使用 sparse-index,速度更快

rust 复制代码
[source.crates-io] 
replace-with = 'rsproxy-sparse' 
[source.rsproxy] 
registry = "https://rsproxy.cn/crates.io-index" 
[source.rsproxy-sparse] 
registry = "sparse+https://rsproxy.cn/index/" 
[registries.rsproxy] 
index = "https://rsproxy.cn/crates.io-index"
[net] 
git-fetch-with-cli = true
相关推荐
啊Q老师5 小时前
Rust异步并发:业务落地的三个关键细节
rust·rust异步并发·业务落地的三个关键细节
小妖同学学AI6 小时前
Rust 深度解析:变量、可变性与所有权的“安全边界”
开发语言·安全·rust
Zhangzy@7 小时前
Rust 内存对齐与缓存友好设计
spring·缓存·rust
G_dou_8 小时前
Trait与泛型高级用法
rust
七月稻草人8 小时前
Rust 应用状态(App State)管理:类型安全与并发控制的艺术
开发语言·安全·rust
人工智能的苟富贵10 小时前
使用 Tauri + Rust 构建跨平台桌面应用:前端技术的新边界
开发语言·前端·rust·electron
2501_9387918311 小时前
Rust Axum 框架开发后端服务:实现高性能 TCP 连接的处理逻辑
网络·tcp/ip·rust
@大迁世界11 小时前
我用 Rust 重写了一个 Java 微服务,然后丢了工作
java·开发语言·后端·微服务·rust
一个努力的小码农11 小时前
Rust中if let与while let语法糖的工程哲学
前端·rust
今日说"法"12 小时前
Rust API 设计中的零成本抽象原则:从原理到实践的平衡艺术
开发语言·后端·rust