Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

使用 cargo install 安装二进制文件

Installing Binaries with cargo install

cargo install 命令允许你在本地安装和使用二进制 crate。这并不是为了取代系统包管理;它是为了方便 Rust 开发者安装他人在 crates.io 上分享的工具。请注意,你只能安装具有二进制目标的包。二进制目标(binary target)是如果 crate 具有 src/main.rs 文件或其他被指定为二进制的文件时创建的可运行程序,与之相对的是库目标(library target),它本身不可运行,但适合包含在其他程序中。通常,crate 会在 README 文件中说明它是库、具有二进制目标还是两者兼有。

The cargo install command allows you to install and use binary crates locally. This isn’t intended to replace system packages; it’s meant to be a convenient way for Rust developers to install tools that others have shared on crates.io. Note that you can only install packages that have binary targets. A binary target is the runnable program that is created if the crate has a src/main.rs file or another file specified as a binary, as opposed to a library target that isn’t runnable on its own but is suitable for including within other programs. Usually, crates have information in the README file about whether a crate is a library, has a binary target, or both.

所有通过 cargo install 安装的二进制文件都存储在安装根目录的 bin 文件夹中。如果你是使用 rustup.rs 安装的 Rust 且没有任何自定义配置,此目录将是 $HOME/.cargo/bin。确保此目录在你的 $PATH 中,以便能够运行通过 cargo install 安装的程序。

All binaries installed with cargo install are stored in the installation root’s bin folder. If you installed Rust using rustup.rs and don’t have any custom configurations, this directory will be $HOME/.cargo/bin. Ensure that this directory is in your $PATH to be able to run programs you’ve installed with cargo install.

例如,在第 12 章中我们提到有一个名为 ripgrep 的用于搜索文件的 grep 工具的 Rust 实现。要安装 ripgrep,我们可以运行以下命令:

For example, in Chapter 12 we mentioned that there’s a Rust implementation of the grep tool called ripgrep for searching files. To install ripgrep, we can run the following:

$ cargo install ripgrep
    Updating crates.io index
  Downloaded ripgrep v14.1.1
  Downloaded 1 crate (213.6 KB) in 0.40s
  Installing ripgrep v14.1.1
--snip--
   Compiling grep v0.3.2
    Finished `release` profile [optimized + debuginfo] target(s) in 6.73s
  Installing ~/.cargo/bin/rg
   Installed package `ripgrep v14.1.1` (executable `rg`)

输出的倒数第二行显示了已安装二进制文件的位置和名称,在 ripgrep 的情况下是 rg。如前所述,只要安装目录在你的 $PATH 中,你就可以运行 rg --help 并开始使用这个更快速、更具 Rust 风格的工具来搜索文件了!

The second-to-last line of the output shows the location and the name of the installed binary, which in the case of ripgrep is rg. As long as the installation directory is in your $PATH, as mentioned previously, you can then run rg --help and start using a faster, Rustier tool for searching files!