依赖项

crates.io 是 Rust 社区的中央包注册中心,用作发现和下载的位置。cargo 默认配置为使用它来查找请求的包。

要依赖于托管在 crates.io 上的库,请将其添加到您的 Cargo.toml 中。

添加依赖项

如果您的 Cargo.toml 尚没有 [dependencies] 部分,请添加它,然后列出您想要使用的 crate 名称和版本。此示例添加了对 time crate 的依赖

[dependencies] time = "0.1.12"

版本字符串是 SemVer 版本要求。指定依赖项文档提供了关于您在此处拥有的选项的更多信息。

如果您还想添加对 regex crate 的依赖,则无需为列出的每个 crate 都添加 [dependencies]。以下是您的整个 Cargo.toml 文件在依赖于 timeregex crate 时看起来的样子

[package] name = "hello_world" version = "0.1.0" edition = "2024" [dependencies] time = "0.1.12" regex = "0.1.41"

重新运行 cargo build,Cargo 将获取新的依赖项及其所有依赖项,编译它们,并更新 Cargo.lock

$ cargo build Updating crates.io index Downloading memchr v0.1.5 Downloading libc v0.1.10 Downloading regex-syntax v0.2.1 Downloading memchr v0.1.5 Downloading aho-corasick v0.3.0 Downloading regex v0.1.41 Compiling memchr v0.1.5 Compiling libc v0.1.10 Compiling regex-syntax v0.2.1 Compiling memchr v0.1.5 Compiling aho-corasick v0.3.0 Compiling regex v0.1.41 Compiling hello_world v0.1.0 (file:///path/to/package/hello_world)

Cargo.lock 包含有关所有这些依赖项所用修订版本的确切信息。

现在,如果 regex 得到更新,您仍然将使用相同的修订版本进行构建,直到您选择运行 cargo update

您现在可以在 main.rs 中使用 regex 库。

use regex::Regex; fn main() { let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap(); println!("Did our date match? {}", re.is_match("2014-01-01")); }

运行它将显示

$ cargo run Running `target/hello_world` Did our date match? true