指定 Cargo 项目所需的 rustc 版本

Specify the version of rustc required for a Cargo project

是否可以指定 Cargo 项目需要最低 rustc 版本,例如 1.1.0 才能编译?

我在 Github 上找到了一些旧提案:

https://github.com/rust-lang/cargo/issues/837
https://github.com/rust-lang/cargo/issues/1044
https://github.com/rust-lang/cargo/issues/1214

他们关闭了

I think that for now there's not a lot actionable in this ticket, I agree that we'll definitely want to re-evaluate post-1.0, but for now I don't think cargo is going to enter the business of supporting various Rust versions as it's just too unstable to track currently.

所以好像还没有办法。也许你应该在那里提出你的案子。

没有

截至目前,您唯一可以实际做的就是在文档 and/or 中记下所需的版本 README 板条箱。

您可以配置 multirust 以使用正确的编译器,但请记住它仅适用于 UNIX-y 环境。

如果您使用 Travis,您可以配置您支持的 Rust 版本和渠道。这是记录它的常用方法。

你可以像这样使用build script

extern crate rustc_version;

use std::io::{self, Write};
use std::process::exit;       
use rustc_version::version_matches;   

fn main() {
    if !version_matches(">= 1.1.0") {
        writeln!(&mut io::stderr(), "This crate requires rustc >= 1.1.0.").unwrap();
        exit(1);
    }   
}

这使用 rustc_version 板条箱。

如果您的项目需要最低 rustc 版本 1.1.0 才能编译,您可以简单地在同一目录中创建一个名为 rust-toolchain 的文件(没有任何文件扩展名)作为您的 Cargo.toml 文件,并向其中添加以下内容:

[toolchain]
channel = "1.1.0"
components = ["rust-src"]

然后当你 运行 cargo build 它会自动下载并安装那个版本并切换到它。有关详细信息,请参阅此 Rust Blog post

Rust RFC #2495 提出了一种未来的替代方法,我们可以将 rust = "1.1.0" 行添加到 Cargo.toml 文件中。

在 Rust 1.56.0 中你可以使用 rust-version:

The rust-version field is an optional key that tells cargo what version of the Rust language and compiler your package can be compiled with. If the currently selected version of the Rust compiler is older than the stated version, cargo will exit with an error, telling the user what version is required.

[package]
rust-version = "1.56"