Rust

Articles in Section

Rust Tools

External links:

  • Rustup toolchain installer - https://rustup.rs/
  • Rustup add-ons needed for formatting and as dependencies:
rustup component add rustfmt 
rustup component add rust-src
  • Install Cargo-watch to rerun code upon save:
cargo install cargo-watch
git clone https://github.com/AstroNvim/AstroNvim ~/.config/nvim
nvim +PackerSync

# After install use commands:
:LspInstall rust -> rust-analyzer
:TSInstall rust
  • Neovide GUI upgrade on Astro Vim
git clone https://github.com/neovide/neovide
cd neovide
cargo build --release
  • EVCXR or iRUST REPL
cargo install evcxr_repl
cargo install irust
cargo install --locked bacon
bacon test # run from project folder 

Cargo

Use Cargo for managing projects.

cargo new test_project // create project with binary file src/main.rs
// OR
cargo new test_project --lib // create project with library file src/lib.rs 

cd test_project

Source code is in src folder.

cargo build # build project for debug, do not run
cargo run # build & run project
cargo check # fast compiling
cargo build --release # slow build with optimizations for speed of release version

Cargo rerun upon saving code:

cargo watch -q -c -x 'run -q'

-x - rerun upon code change -c - clear terminal each time -q - quiet mode

Documentation of methods & traits used in code can be compiled an opened in browser with Cargo command:

cargo doc --open

Cargo Examples

Create “examples” folder beside the “src” folder. Create a file named, for example, “variables.rs” and place some test code in the folder. Then in the project root folder run:

cargo run --example variables

This will compile+build the code in examples folder, file “variables.rs”. Very convenient to try test different stuff. For live development do:

cargo watch -q -c -x 'run -q --example variables'

Panic Response

В ответ на панику, по умолчанию программа разматывает стек (unwinding) - проходит по стеку и вычищает данные всех функций. Для уменьшения размера можно просто отключать программу без очистки - abort. Для этого в файле Cargo.toml надо добавить в разделы [profile]:

[profile.release]
panic = 'abort'

Cargo Clippy linter

Example of Clippy config:

cargo clippy --fix -- \
-W clippy::pedantic \
-W clippy::nursery \
-W clippy::unwrap_used \
-W clippy::expect_used

Clippy has a markdown book:

cargo install mdbook
# Run from top level of your rust-clippy directory:
mdbook serve book --open
# Goto http://localhost:3000 to see the book

Important Cargo libs

  • Tokio - async runtime
  • Eyre & color-eyre - type signatures, error report handling
  • Tracing - collect diagnostic info
  • Reqwest - HTTP requests library, async
  • Rayon - data parallelism library, without data races
  • Clap - commandline passing library
  • SQLX - compile-checked SQL, async
  • Chrono - time/date library
  • EGUI - web-gui @60FPS, runs in Webassembly
  • Yew.rs - web-library like React.js

Cargo OFFLINE

Для создания локального сервера можно скачать все пакеты Cargo с помощью проекта Panamax.

cargo install --locked panamax
panamax init ~/test/my-mirror

Нужно зайти в папку my-mirror, проверить настройки в файле mirror.toml. И далее запустить синхронизацию:

panamax sync ~/test/my-mirror

Далее, можно публиковать зеркало по веб через встроенный сервер (по порту 8080):

panamax serve ~/test/my-mirror

На индекс странице сервера будет справка по подключению Rust клиентов к зеркалу. В частности, посредством создания файла настроек ~/.cargo/config :

[source.my-mirror]
registry = "http://panamax.local/crates.io-index"
[source.crates-io]
replace-with = "my-mirror"

Rust Prelude

Rust has a Prelude - a set of libraries included in every project. See current libs included in Prelude

Allow Unused

Turn off noise about unused objects while learning with a crate attribute:

#![allow(unused)] // silence unused warnings while learning
fn main() {}

User input

std::io::stdin library is used to get user input from standard input stream. Not included in Prelude:

use std:io

let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("Failed to load");

.expect handles Err variant of read_line function, crashing the program with the defined error message.