文章

rust 工具链切换 toolchain

rust 工具链切换 toolchain

rust 项目编译时关于 toolchain 切换问题的记录

背景

无意执行了更新工具链的命令,导致原有项目编译报错,报错的原因可能是新版本工具链在一些语法上要求更为严格,比如名称相似的 type 会报错

1
2
3
4
5
6
7
8
9
10
11
error[E0432]: unresolved import `zstd_sys::ZSTD_cParameter::ZSTD_c_experimentalParam6`
   --> /Users/mochi/.cargo/registry/src/index.crates.io-6f17d22bba15001f/zstd-safe-6.0.6/src/lib.rs:609:13
    |
609 |             ZSTD_c_experimentalParam6 as ZSTD_c_targetCBlockSize,
    |             -------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |             |
    |             no `ZSTD_c_experimentalParam6` in `ZSTD_cParameter`
    |             help: a similar name exists in the module: `ZSTD_c_experimentalParam1`

For more information about this error, try `rustc --explain E0432`.
error: could not compile `zstd-safe` (lib) due to 1 previous error

更新 stable 工具链为最新版本的命令如下:

1
❯ rustup update stable

这里先介绍下 rustup、rustc、cargo 等工具之间的关系,rustup 是 rust 语言的安装器以及版本管理工具,我们会使用 rustup 进行 rust 工具链的版本管理,每个版本的工具链都会包含很多工具,比如:

  • rustc 是 rust 的编译器,负责将 rust 代码编译为可执行文件,或者是库
  • cargo 是 rust 的包管理器以及构建工具,能够帮助用户管理项目依赖,构建以及运行测试,文档生成,发布库。
  • rustdoc 是从 rust 源码生成文档的工具
  • 还有很多其他工具,如 rust-std、rustfmt、clippy(静态代码分析工具)、cargo-clippy

在安装某特定版本时可以看到它安装的工具

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
❯ rustup toolchain install 1.79.0                                                                            
info: syncing channel updates for '1.79.0-aarch64-apple-darwin'
info: latest update on 2024-06-13, rust version 1.79.0 (129f3b996 2024-06-10)
info: downloading component 'cargo'
info: downloading component 'clippy'
info: downloading component 'rust-docs'
info: downloading component 'rust-std'
info: downloading component 'rustc'
 50.9 MiB /  50.9 MiB (100 %)  21.1 MiB/s in  2s ETA:  0s
info: downloading component 'rustfmt'
info: installing component 'cargo'
info: installing component 'clippy'
info: installing component 'rust-docs'
 15.4 MiB /  15.4 MiB (100 %)   3.4 MiB/s in  3s ETA:  0s
info: installing component 'rust-std'
 22.7 MiB /  22.7 MiB (100 %)  18.7 MiB/s in  1s ETA:  0s
info: installing component 'rustc'
 50.9 MiB /  50.9 MiB (100 %)  19.4 MiB/s in  2s ETA:  0s
info: installing component 'rustfmt'

使用如下命令可以切换 rustup 工具链的版本(当前文件夹)

1
❯ rustup  default 1.79.0         

在更新工具链之前强烈建议先看清楚当前的版本号是多少,避免后续出问题了不知道怎么回退。直接看 cargo 版本号就行。

1
❯ cargo version

展示当前安装的所有工具链

1
2
3
❯ rustup toolchain list --verbose
stable-aarch64-apple-darwin (default)   /Users/mochi/.rustup/toolchains/stable-aarch64-apple-darwin
1.78-aarch64-apple-darwin       /Users/mochi/.rustup/toolchains/1.78-aarch64-apple-darwin
本文由作者按照 CC BY 4.0 进行授权