侧边栏壁纸
  • 累计撰写 94 篇文章
  • 累计创建 35 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

Rust入门:从安装到依赖管理

天明
2024-01-17 / 0 评论 / 0 点赞 / 52 阅读 / 4796 字 / 正在检测是否收录...

1.安装rust

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

rustc --version

# 更新与卸载
rustup update
rustup self uninstall

2.Cargo - Rust内置的构建系统及包管理器

cargo new <pro_name> 创建项目
cargo build [--release] -v 可以构建项目
cargo clean 删除target目录
cargo search 查找依赖
cargo add 添加依赖
cargo remove 删除依赖
cargo tree 查看依赖
cargo update 更新依赖
cargo run 运行项目
cargo test -v 运行测试
cargo doc --no-deps 生成项目文档
cargo publish 可以将库发布到 crates.io。
cargo login --registry crates-io
cargo logout --registry crates-io
cargo publish --registry crates-io --dry-run
# 使用rustc编译
rustc src/main.rs
./main # 运行
# 添加
cargo add regex
cargo add --dev trybuild
cargo add nom@5
# 更新指定依赖
cargo update regex

2.1 Cargo.toml依赖版本设置

log = "1.2.3"
// ^
log = "^1.2.3" # 指定最低版本要求
// ~
~1.2.3  := >=1.2.3, <1.3.0
~1.2    := >=1.2.0, <1.3.0
~1      := >=1.0.0, <2.0.0
// *
*     := >=0.0.0
1.*   := >=1.0.0, <2.0.0
1.2.* := >=1.2.0, <1.3.0
//
>= 1.2.0
> 1
< 2
= 1.2.3
// 范围指定
">=0.4, <2"
// 仓库指定
[dev-dependencies]
tempdir = "0.3"

[build-dependencies]
cc = "1.0.3"

[dependencies]
some-crate = { version = "1.0", registry = "my-registry" }
regex = { git = "https://github.com/rust-lang/regex.git" }
regex = { git = "https://github.com/rust-lang/regex.git", branch = "next" }
// 项目路径
hello_utils = { path = "hello_utils" }
hello_utils = { path = "hello_utils", version = "0.1.0" }
// 依赖别名
bar = { git = "https://github.com/example/project.git", package = "foo" }
baz = { version = "0.1", registry = "custom", package = "foo" }
// 不同平台
[target.'cfg(windows)'.dependencies]
winhttp = "0.4.0"
[target.'cfg(unix)'.dependencies]
openssl = "1.0.1"
[target.'cfg(target_arch = "x86")'.dependencies]
native-i686 = { path = "native/i686" }
[target.'cfg(target_arch = "x86_64")'.dependencies]
native-x86_64 = { path = "native/x86_64" }

2.2 私有registry

// $HOME/.cargo/config.toml
[registry]
default = "my-registry"

[registries]
my-registry = { index = "https://my-intranet:8080/git/index" }
// $HOME/.cargo/credentials.toml
[registries.my-registry]
token = "854DvwSlUwEHtIo3kWy6x7UCPKHfzCmy"

// Cargo.toml
[dependencies]
other-crate = { version = "1.0", registry = "my-registry" }

国内加速

# 步骤一:设置 Rustup 镜像, 修改配置 ~/.zshrc or ~/.bashrc
export RUSTUP_DIST_SERVER="https://rsproxy.cn"
export RUSTUP_UPDATE_ROOT="https://rsproxy.cn/rustup"
# 步骤二:安装 Rust(请先完成步骤一
curl --proto '=https' --tlsv1.2 -sSf https://rsproxy.cn/rustup-init.sh | sh
# 步骤三:设置镜像,修改配置~/.cargo/config,已支持git协议和sparse协议,>=1.68 版本建议使用 sparse-index,速度更快。
[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
0

评论区