rust cargo_Rust包管理器Cargo入门

rust cargo

Rust是一种现代编程语言,可提供性能,可靠性和生产率。 数年来,它一直被StackOverflow调查评为最受喜爱的语言

除了成为一种出色的编程语言外,Rust还具有一个称为Cargo的构建系统和软件包管理器。 Cargo处理许多任务,例如构建代码,下载库或依赖项等等。 两者捆绑在一起,因此在安装Rust时会得到Cargo。

安装防锈和货物

在开始之前,您需要安装Rust和Cargo。 Rust项目提供了可下载的脚本来处理安装。 要获取脚本,请打开浏览器到https://sh.rustup.rs并保存文件。 阅读脚本以确保您对它打算做什么感到满意,然后运行它:

 $ sh . / rustup.rs  

您也可以参考Install Rust网页以获取更多信息。

安装Rust和Cargo之后,您必须获取环境文件:

 $ source $HOME / .cargo / env 

更好的是,将所需目录添加到PATH变量中:

 $ source $HOME / .cargo / env 

如果您更喜欢使用软件包管理器(例如Linux上的DNF或Apt),请在发行版本的存储库中查找Rust和Cargo软件包并进行相应安装。 例如:

 $ dnf install rust cargo 

安装并设置它们后,请验证您具有的Rust和Cargo版本:


   
   
$ rustc --version
rustc 1.41.0 ( 5e1a79984 2020 -01- 27 )
$ cargo --version
cargo 1.41.0 ( 626f0f40e 2019 - 12 -03 )

手动构建和运行Rust

从打印“你好,世界!”的简单程序开始。 屏幕上。 打开您喜欢的文本编辑器,然后键入以下程序:


   
   
$ cat hello.rs
fn main() {
    println!("Hello, world!");
}

保存扩展名为.rs的文件,以将其标识为Rust源代码文件。

使用Rust编译器rustc编译程序:

 $ rustc hello.rs 

编译后,您将拥有一个与源程序同名的二进制文件:


   
   
$ ls - l
total 2592
- rwxr - xr - x. 1 user group 2647944 Feb 13 14 : 14 hello
- rw - r -- r -- . 1 user group       45 Feb 13 14 : 14 hello.rs
$

执行程序以验证其是否按预期运行:


   
   
$ . / hello
Hello , world !

这些步骤对于较小的程序或任何您想快速测试的东西就足够了。 但是,在进行涉及多个人的大型计划时,货运是前进的最佳方式。

使用货运创建新包裹

Rust社区提供的常见问题解答 ,以进行澄清。

如果您需要有关Cargo命令行实用程序的任何帮助,请使用--help-h命令行参数:

 $ cargo –help 

要创建新程序包,请使用new关键字,后跟程序包名称。 对于此示例,使用hello_opensource作为新的程序包名称。 运行该命令后,您将看到一条消息,确认Cargo已使用给定名称创建了一个二进制软件包:


   
   
$ cargo new hello_opensource
     Created binary ( application ) `hello_opensource` package

运行命令以查看目录结构会报告已创建了一些文件和目录。 首先,它创建一个带有包名称的目录,并且在该目录内是源代码文件的src目录:


   
   
$ tree .
.
└── hello_opensource
    ├── Cargo.toml
    └── src
        └── main.rs

2 directories , 2 files

货运不仅可以创建包裹,还可以创建一个简单的Hello world世界! 程序。 打开main.rs文件,看看:


   
   
$ cat hello_opensource / src / main.rs
fn main ( ) {
    println ! ( "Hello, world!" ) ;
}

下一个要使用的文件是Cargo.toml ,这是您的软件包的配置文件。 它包含有关软件包的信息,例如其名称,版本,作者信息和Rust版本信息。

程序通常依赖于外部库或依赖项来运行,这使您可以编写应用程序来执行不知道如何编码或不想花时间编码的任务。 您所有的依赖项都将在此文件中列出。 此时,您对新程序没有任何依赖关系。 打开Cargo.toml文件并查看其内容:


   
   
$ cat hello_opensource / Cargo.toml
[ package ]
name = "hello_opensource"
version = "0.1.0"
authors = [ "user <user@mail.com>" ]
edition = "2018"

# See more keys and their definitions at https : //doc.rust-lang.org/cargo/reference/manifest.html

[ dependencies ]

使用Cargo构建程序

到目前为止,一切都很好。 现在您已经有了一个包,构建一个二进制文件(也称为可执行文件)。 在此之前,进入package目录:

 $ cd hello_opensource / 

您可以使用Cargo的build命令来构建软件包。 请注意以下消息,指出它正在编译程序:


   
   
$ cargo build
   Compiling hello_opensource v0.1.0 ( / opensource / hello_opensource )
    Finished dev [ unoptimized + debuginfo ] target ( s ) in 0.38s

运行build命令后,检查项目目录发生了什么:


   
   
$ tree .
.
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
└── target
    └── debug
        ├── build
        ├── deps
        │   ├── hello_opensource - 147b8a0f466515dd
        │   └── hello_opensource - 147b8a0f466515dd.d
        ├── examples
        ├── hello_opensource
        ├── hello_opensource.d
        └── incremental
            └── hello_opensource - 3pouh4i8ttpvz
                ├── s - fkmhjmt8tj - x962ep - 1hivstog8wvf
                │   ├── 1r37g6m45p8rx66m.o
                │   ├── 2469ykny0eqo592v.o
                │   ├── 2g5i2x8ie8zed30i.o
                │   ├── 2yrvd7azhgjog6zy.o
                │   ├── 3g9rrdr4hyk76jtd.o
                │   ├── dep - graph.bin
                │   ├── query - cache.bin
                │   ├── work - products.bin
                │   └── wqif2s56aj0qtct.o
                └── s - fkmhjmt8tj - x962ep.lock

9 directories , 17 files

哇! 编译过程产生了许多中间文件。 但是,您的二进制文件将以与软件包相同的名称保存在./target/debug目录中。

使用货运运行您的应用程序

既然您的二进制文件已经构建,请使用Cargo的run命令运行它。 正如预期的那样,它将打印Hello,世界! 屏幕上。


   
   
$ cargo run
    Finished dev [ unoptimized + debuginfo ] target ( s ) in 0.01s
     Running `target / debug / hello_opensource`
Hello , world !

或者,您可以直接运行二进制文件,该文件位于:


   
   
$ ls - l . / target / debug / hello_opensource
- rwxr - xr - x. 2 root root 2655552 Feb 13 14 : 19 . / target / debug / hello_opensource

正如预期的那样,它会产生相同的结果:


   
   
$ . / target / debug / hello_opensource
Hello , world !

假设您需要重建软件包,并摆脱早期编译过程创建的所有二进制文件和中间文件。 Cargo提供了一个方便的清理选项,可删除除源代码和其他所需文件以外的所有中间文件:


   
   
$ cargo clean
$ tree .
.
├── Cargo.lock
├── Cargo.toml
└── src
    └── main.rs

1 directory , 3 files

对程序进行一些更改,然后再次运行以查看其工作方式。 例如,此较小的更改将Opensource添加到Hello世界! 串:


   
   
$ cat src / main.rs
fn main ( ) {
    println ! ( "Hello, Opensource world!" ) ;
}

现在,生成程序并再次运行。 这次您会看到“ 开源世界,您好!” 在屏幕上显示:


   
   
$ cargo build
   Compiling hello_opensource v0.1.0 ( / opensource / hello_opensource )
    Finished dev [ unoptimized + debuginfo ] target ( s ) in 0.39s

$ cargo run
    Finished dev [ unoptimized + debuginfo ] target ( s ) in 0.01s
     Running `target / debug / hello_opensource`
Hello , Opensource world !

使用货运添加依赖项

Cargo允许您添加程序需要运行的依赖项。 使用Cargo添加依赖非常容易。 每个Rust软件包都包含一个Cargo.toml文件,该文件包含一个依赖关系列表(默认情况下为空)。 在您喜欢的文本编辑器中打开文件,找到[dependencies]部分,然后添加要包含在包中的库。 例如,要将rand库添加为依赖项:


   
   
$ cat Cargo.toml
[ package ]
name = "hello_opensource"
version = "0.1.0"
authors = [ "test user <test@mail.com>" ]
edition = "2018"

# See more keys and their definitions at https : //doc.rust-lang.org/cargo/reference/manifest.html

[ dependencies ]
rand = "0.3.14"

尝试构建您的包,看看会发生什么。


   
   
$ cargo build
    Updating crates.io index
   Compiling libc v0.2.66
   Compiling rand v0.4.6
   Compiling rand v0.3.23
   Compiling hello_opensource v0.1.0 ( / opensource / hello_opensource )
    Finished dev [ unoptimized + debuginfo ] target ( s ) in 4.48s

Cargo现在正在联系Crates.io ,这是Rust的板条箱(或包裹)以及rand的下载和编译中心。 但是,等等-libc软件包怎么样? 您没有要求安装libc 。 好吧, rand包依赖于libc包; 因此,Cargo也会下载并编译libc

库的新版本不断涌现,而Cargo提供了一种使用update命令更新其所有依赖项的简便方法:

 cargo update 

您还可以选择使用-p标志和包名来更新特定的库:

 cargo update - p rand 

使用单个命令进行编译和运行

到目前为止,每当对程序进行更改时,您都先使用了build,然后运行了 。 有一种更简单的方法:您可以简单地使用run命令,该命令在内部编译并运行该程序。 要查看其工作原理,请首先清理您的软件包目录:


   
   
$ cargo clean
$ tree .
.
├── Cargo.lock
├── Cargo.toml
└── src
    └── main.rs

1 directory , 3 files

现在执行run 。 输出表明它已编译然后运行程序,这意味着您无需每次都显式运行build


   
   
$ cargo run
   Compiling hello_opensource v0.1.0 ( / opensource / hello_opensource )
    Finished dev [ unoptimized + debuginfo ] target ( s ) in 0.41s
     Running `target / debug / hello_opensource`
Hello , world !

在开发中检查代码

开发程序时,您经常会经历多次迭代。 您需要确保您的程序没有编码错误并且可以正常编译。 您不需要在每次编译时生成二进制文件的开销。 Cargo为您提供了一个检查选项,该选项可以编译代码,但跳过生成可执行文件的最后一步。

首先在您的包裹目录中运行clean clean


   
   
$ tree .
.
├── Cargo.lock
├── Cargo.toml
└── src
    └── main.rs

1 directory , 3 files

现在运行check命令,查看对目录进行了哪些更改:


   
   
$ cargo check
    Checking hello_opensource v0.1.0 ( / opensource / hello_opensource )
    Finished dev [ unoptimized + debuginfo ] target ( s ) in 0.18s

输出显示,即使在编译过程中创建了中间文件,也没有创建最终的二进制文件或可执行文件。 这样可以节省一些时间,如果该程序包包含数千行代码,则非常重要:


   
   
$ tree .
.
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
└── target
    └── debug
        ├── build
        ├── deps
        │   ├── hello_opensource - 842d9a06b2b6a19b.d
        │   └── libhello_opensource - 842d9a06b2b6a19b.rmeta
        ├── examples
        └── incremental
            └── hello_opensource - 1m3f8arxhgo1u
                ├── s - fkmhw18fjk - 542o8d - 18nukzzq7hpxe
                │   ├── dep - graph.bin
                │   ├── query - cache.bin
                │   └── work - products.bin
                └── s - fkmhw18fjk - 542o8d.lock

9 directories , 9 files

要查看您是否真的在节省时间,请安排构建时间并检查命令并进行比较。

首先, 构建命令:


   
   
$ time cargo build
   Compiling hello_opensource v0.1.0 ( / opensource / hello_opensource )
    Finished dev [ unoptimized + debuginfo ] target ( s ) in 0.40s

real    0m0.416s
user    0m0.251s
sys     0m0.199s

运行check命令之前, 清理目录:

 $ cargo clean 

检查命令:


   
   
$ time cargo check
    Checking hello_opensource v0.1.0 ( / opensource / hello_opensource )
    Finished dev [ unoptimized + debuginfo ] target ( s ) in 0.15s

real    0m0.166s
user    0m0.086s
sys     0m0.081s

显然, 检查命令要快得多。

构建外部Rust包

到目前为止,您所做的一切都将应用于您从互联网上获得的任何Rust板条箱。 您只需要下载或克隆存储库,移至package文件夹,然后运行build命令,就可以了:


   
   
git clone < github - like - url >
cd < package - folder >
cargo build

使用货运构建优化的Rust程序

到目前为止,您已经运行了多次构建 ,但是您注意到它的输出了吗? 不用担心,再次构建它并密切注意:


   
   
$ cargo build
   Compiling hello_opensource v0.1.0 ( / opensource / hello_opensource )
    Finished dev [ unoptimized + debuginfo ] target ( s ) in 0.36s

每次编译后都看到[unoptimized + debuginfo]文本吗? 这意味着Cargo生成的二进制文件包含许多调试信息,并且未针对执行进行优化。 开发人员经常经历开发的多次迭代,并且需要此调试信息进行分析。 而且,性能并不是开发软件时的近期目标。 因此,现在可以。

但是,一旦准备好发布软件,就不再需要调试信息。 但是,确实需要对其进行优化以获得最佳性能。 在开发的最后阶段,可以将--release标志与build一起使用 。 盯紧了; 编译后,您应该会看到[优化的]文本:


   
   
$ cargo build -- release
   Compiling hello_opensource v0.1.0 ( / opensource / hello_opensource )
    Finished release [ optimized ] target ( s ) in 0.29s

如果需要,您可以通过练习来了解运行优化软件与未优化软件时节省的时间。

使用Cargo创建库与二进制文件

任何软件程序都可以粗略地分类为独立的二进制文件或库。 即使可以使用外部库,也可以按原样运行独立的二进制文件。 但是,另一个独立的二进制文件利用了一个库。 到目前为止,您在本教程中构建的所有程序都是独立的二进制文件,因为这是Cargo的默认设置。 要创建 ,请添加--lib选项:


   
   
$ cargo new -- lib libhello
     Created library `libhello` package

这次,Cargo不创建main.rs文件; 而是创建一个lib.rs文件。 您的库的代码应该在这里:


   
   
$ tree .
.
└── libhello
    ├── Cargo.toml
    └── src
        └── lib.rs

2 directories , 2 files

了解Cargo,不要惊讶于它在您的新库文件中添加了一些代码。 通过移至软件包目录并查看文件来查找添加的内容。 默认情况下,Cargo在库文件中放置一个测试函数。

使用货运进行测试

Rust为单元和集成测试提供了一流的支持,而Cargo允许您执行以下任何测试:


   
   
$ cd libhello /

$ cat src / lib.rs
# [ cfg ( test ) ]
mod tests {
    # [ test ]
    fn it_works ( ) {
        assert_eq ! ( 2 + 2 , 4 ) ;
    }
}

Cargo有一个方便的测试选项,可以运行代码中存在的任何测试。 尝试默认运行Cargo在库代码中放入的测试:


   
   
$ cargo test
   Compiling libhello v0.1.0 ( / opensource / libhello )
    Finished test [ unoptimized + debuginfo ] target ( s ) in 0.55s
     Running target / debug / deps / libhello - d52e35bb47939653

running 1 test
test tests :: it_works ... ok

test result : ok. 1 passed ; 0 failed ; 0 ignored ; 0 measured ; 0 filtered out

   Doc - tests libhello

running 0 tests

test result : ok. 0 passed ; 0 failed ; 0 ignored ; 0 measured ; 0 filtered out

看着货物的引擎盖

您可能有兴趣在运行命令时了解Cargo的功能。 毕竟,货物在许多方面都是包装纸。 要了解它在做什么,您可以将-v选项与任何Cargo命令一起使用,以将详细信息输出到屏幕。

以下是几个使用-v选项运行buildclean的示例。

build命令中,您可以看到使用指定的命令行选项触发了底层rustc (Rust编译器):


   
   
$ cargo build - v
   Compiling hello_opensource v0.1.0 ( / opensource / hello_opensource )
     Running `rustc -- edition = 2018 -- crate - name hello_opensource src / main.rs -- error - format = json -- json = diagnostic - rendered - ansi -- crate - type bin -- emit = dep - info , link - C debuginfo = 2 - C metadata = 147b8a0f466515dd - C extra - filename =- 147b8a0f466515dd -- out - dir / opensource / hello_opensource / target / debug / deps - C incremental =/ opensource / hello_opensource / target / debug / incremental - L dependency =/ opensource / hello_opensource / target / debug / deps`
    Finished dev [ unoptimized + debuginfo ] target ( s ) in 0.36s

clean命令显示它只是删除包含中间文件和二进制文件的目录:


   
   
$ cargo clean - v
    Removing / opensource / hello_opensource / target

不要让你的技能生锈

要扩展您的技能,请尝试使用Rust和Cargo编写并运行一个稍微复杂的程序。 简单的操作就可以做到:例如,尝试列出当前目录中的所有文件(可以用9行代码完成),或者尝试自己回显输入。 小型练习应用程序可帮助您熟悉语法以及编写和测试代码的过程。

本文为刚起步的Rust程序员提供了很多信息,以帮助他们开始使用Cargo。 但是,当您开始处理更大,更复杂的程序时,您需要对Cargo有更深入的了解。 当您准备就绪时,请下载并阅读Rust团队编写的开源《 货运手册》 ,并查看可以创建的内容!

翻译自: https://opensource.com/article/20/3/rust-cargo

rust cargo

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值