Cargo
Профили релизов
профили выпуска — это предопределённые и настраиваемые профили с различными конфигурациями, которые позволяют программисту лучше контролировать различные параметры компиляции кода. Каждый профиль настраивается независимо от других.
Cargo имеет два основных профиля: профиль
dev, используемый Cargo при запускеcargo build, и профильrelease, используемый Cargo при запускеcargo build --release.
Файл: Cargo.toml
Настройка количества оптимизаций opt-level
[profile.dev]
opt-level = 0
[profile.release]
opt-level = 3
cargo --list ✔
Installed Commands:
add Add dependencies to a Cargo.toml manifest file
audit
b alias: build
bench Execute all benchmarks of a local package
build Compile a local package and all of its dependencies
c alias: check
check Check a local package and all of its dependencies for errors
clean Remove artifacts that cargo has generated in the past
clippy Checks a package to catch common mistakes and improve your Rust code.
config Inspect configuration values
d alias: doc
doc Build a package's documentation
fetch Fetch dependencies of a package from the network
fix Automatically fix lint warnings reported by rustc
fmt Formats all bin and lib files of the current crate using rustfmt.
generate-lockfile Generate the lockfile for a package
git-checkout REMOVED: This command has been removed
help Displays help for a cargo subcommand
info Display information about a package
init Create a new cargo package in an existing directory
install Install a Rust binary
locate-project Print a JSON representation of a Cargo.toml file's location
login Log in to a registry.
logout Remove an API token from the registry locally
metadata Output the resolved dependencies of a package, the concrete used versions including overrides, in machine-readable format
miri
new Create a new cargo package at <path>
outdated
owner Manage the owners of a crate on the registry
package Assemble the local package into a distributable tarball
pkgid Print a fully qualified package specification
publish Upload a package to the registry
r alias: run
read-manifest DEPRECATED: Print a JSON representation of a Cargo.toml manifest.
remove Remove dependencies from a Cargo.toml manifest file
report Generate and display various kinds of reports
rm alias: remove
run Run a binary or example of the local package
rustc Compile a package, and pass extra options to the compiler
rustdoc Build a package's documentation, using specified custom flags.
search Search packages in the registry. Default registry is crates.io
t alias: test
test Execute all unit and integration tests and build examples of a local package
tree Display a tree visualization of a dependency graph
uninstall Remove a Rust binary
update Update dependencies as recorded in the local lock file
vendor Vendor all dependencies for a project locally
verify-project DEPRECATED: Check correctness of crate manifest.
version Show version information
yank Remove a pushed crate from the index
cargo --help ✔
Rust's package manager
Usage: cargo [+toolchain] [OPTIONS] [COMMAND]
cargo [+toolchain] [OPTIONS] -Zscript <MANIFEST_RS> [ARGS]...
Options:
-V, --version Print version info and exit
--list List installed commands
--explain <CODE> Provide a detailed explanation of a rustc error message
-v, --verbose... Use verbose output (-vv very verbose/build.rs output)
-q, --quiet Do not print cargo log messages
--color <WHEN> Coloring [possible values: auto, always, never]
-C <DIRECTORY> Change to DIRECTORY before doing anything (nightly-only)
--locked Assert that `Cargo.lock` will remain unchanged
--offline Run without accessing the network
--frozen Equivalent to specifying both --locked and --offline
--config <KEY=VALUE|PATH> Override a configuration value
-Z <FLAG> Unstable (nightly-only) flags to Cargo, see 'cargo -Z help' for details
-h, --help Print help
Commands:
build, b Compile the current package
check, c Analyze the current package and report errors, but don't build object files
clean Remove the target directory
doc, d Build this package's and its dependencies' documentation
new Create a new cargo package
init Create a new cargo package in an existing directory
add Add dependencies to a manifest file
remove Remove dependencies from a manifest file
run, r Run a binary or example of the local package
test, t Run the tests
bench Run the benchmarks
update Update dependencies listed in Cargo.lock
search Search registry for crates
publish Package and upload this package to the registry
install Install a Rust binary
uninstall Uninstall a Rust binary
... See all commands with --list
See 'cargo help <command>' for more information on a specific command.
Публикация библиотеки в Crates.io
Реестр библиотек по адресу crates.io распространяет исходный код ваших пакетов, поэтому он в основном размещает код с открытым исходным кодом.
- Комментарии к документации используют три слеша, /// вместо двух и поддерживают нотацию Markdown для форматирования текста.
- Размещайте комментарии к документации непосредственно перед элементом, который они документируют.
cargo doc --open— откроет документацию в браузереcargo test— запустит примеры как тесты- //! добавит комментарии ко всему документу указать в начале файла
Использование подмодулей
Для удобного документирования в главном модуле используем реэкспорт
#![allow(unused)] fn main() { //! # Art //! //! A library for modeling artistic concepts. pub use self::kinds::PrimaryColor; pub use self::kinds::SecondaryColor; pub use self::utils::mix; pub mod kinds { // --snip-- } pub mod utils { // --snip-- } }
регистрация на Crate.io
- регистрация по GitHub
- Получение токен
cargo login abcdefghijklmnopqrstuvwxyz012345логин и сохранение токен
Публикация crate
- Подобрать уникальное имя crate в файле
crate.toml
[package]
name = "guessing_game"
cargo publish— опубликовать- Перед публикацией вид файла
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2021"
description = "A fun game where you guess what number the computer has chosen."
license = "MIT OR Apache-2.0"
[dependencies]
Вычеркивание версии cargo yank
Рабочее пространство
Workspace - это набор пакетов, которые используют один и тот же Cargo.lock и директорию для хранения результатов компиляции.
- Ручками создать главный
Cargo.toml - Прописать в нем пути к бинарному крейту и библиотечным крейтам
[workspace]
resolver = "3"
members = ["adder", "add_one"]
├── Cargo.lock
├── Cargo.toml
├── add_one
│ ├── Cargo.toml
│ └── src
│ └── lib.rs
├── adder
│ ├── Cargo.toml
│ └── src
│ └── main.rs
└── target
- Во внутренних крейтах прописать зависимости к библиотекам Workspace
[dependencies]
add_one = { path = "../add_one" }
- Использование функций в коде
fn main() { let num = 10; println!("Hello, world! {num} plus one is {}!", add_one::add_one(num)); }
Установка бинарников с crate.io
cargo install ripgrep