codecamp

Cargo 依赖

从 crates.io 添加依赖项

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

获取托管在crates.io的依赖'库',将它添加到您的Cargo.toml.

添加依赖项

如果你的Cargo.toml,还没有[dependencies]部分,添加它,然后列出您要使用的包名称和版本。这个例子增加了一个time箱(crate)依赖:

[dependencies]
time = "0.1.12"

版本字符串是semver版本要求。该指定依赖项文档 提供了有关此处选项的更多信息.

如果我们还想添加一个regex箱子依赖,我们不需要为每个箱子都添加[dependencies]。下面就是你的Cargo.toml文件整体,看起来像依赖于timeregex箱:

[package]
name = "hello_world"
version = "0.1.0"
authors = ["Your Name <you@example.com>"]

[dependencies]
time = "0.1.12"
regex = "0.1.41"

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

$ cargo build
      Updating registry `https://github.com/rust-lang/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/project/hello_world)

我们的Cargo.lock包含有关,我们使用的所有这些依赖项的哪个版本的确实信息.

现在,如果regexcrates.io上更新了,在我们选择cargo update之前,我们仍会使用相同的版本进行构建.

你现在可以使用regex箱了,通过在main.rs使用extern crate

extern crate 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


Cargo 处理现有的包
Cargo 包装布局
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

Cargo 常见问题

Cargo 附录:词汇表

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }