從 crates.io 添加依賴項
crates.io是 Rust 社區(qū)的中央存儲庫,用作發(fā)現(xiàn)和下載包的位置。cargo
默認配置為,使用它來查找請求的包.
獲取托管在crates.io的依賴'庫',將它添加到您的Cargo.toml
.
添加依賴項
如果你的Cargo.toml
,還沒有[dependencies]
部分,添加它,然后列出您要使用的包名稱和版本。這個例子增加了一個time
箱(crate)依賴:
[dependencies]
time = "0.1.12"
版本字符串是semver版本要求。該指定依賴項文檔 提供了有關此處選項的更多信息.
如果我們還想添加一個regex
箱子依賴,我們不需要為每個箱子都添加[dependencies]
。下面就是你的Cargo.toml
文件整體,看起來像依賴于time
和regex
箱:
[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
包含有關,我們使用的所有這些依賴項的哪個版本的確實信息.
現(xiàn)在,如果regex
在crates.io上更新了,在我們選擇cargo update
之前,我們仍會使用相同的版本進行構建.
你現(xiàn)在可以使用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
更多建議: