Skip to content

Latest commit

 

History

History
291 lines (228 loc) · 12 KB

rust.md

File metadata and controls

291 lines (228 loc) · 12 KB

Rust

Books

Articles, blogs, and courses

Getting started

Install system packages

# Make sure rust isn't installed, because we'll use `rustup` to manage rust and cargo installations
# Linux: apt remove cargo rust
# macOS: brew uninstall rust

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Ensure that ~/.cargo/env is sourced in your environment. rustup may update ~/.bashrc, ~/.profile, and/or ~/.zshenv accordingly, but you may wish to modify these files according to your needs.

if [[ -f "${HOME}/.cargo/env" ]]; then
    source "${HOME}/.cargo/env"
fi

Update Rust on the stable, beta, or nightly channel

#channel=beta
#channel=nightly
channel=stable
rustup update ${channel}
rustup default ${channel}

Create a project

# Use the binary template by default: --bin
cargo new ${project_name}

# Or use the library template: --lib
# cargo new --lib ${library_project_name}

cd ${project_name}
vim Cargo.toml

# Use the toolchain from the nightly channel for this project/directory
rustup override set nightly

cargo build
cargo run

Testing

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_add() {
        assert_eq!(add(1, 2), 3);
    }

    use test_case::test_case;

    #[test_case(-2, -4 ; "when both operands are negative")]
    #[test_case(2,  4  ; "when both operands are positive")]
    #[test_case(4,  2  ; "when operands are swapped")]
    fn multiplication_tests(x: i8, y: i8) {
        let actual = (x * y).abs();

        assert_eq!(8, actual)
    }
}

Run tests using Cargo

# Display one character per test instead of one line
# Test only this package's library unit tests
cargo test --quiet --lib

# Run all tests whose name matches `*navigate*`
cargo test navigate

# Run tests in a module and its submodules
cargo test views::

# Run tests in a module, but not its submodules
cargo test views::tests

Macros

Features and crate-level configuration:

// Requires Rust from the nightly channel as of rustc 1.59.0-nightly (e012a191d 2022-01-06)
#![feature(mixed_integer_ops)]

// Allow modules to have the same name as their parent module
#![allow(clippy::module_inception)]

// Show more lint warnings
#![warn(clippy::all, clippy::pedantic)]

Cargo

# List features enabled for each dependency
cargo tree -f "{p} {f}"

# More verbose version of the above
cargo tree -e features

# Fix issues
cargo fix

# Fix issues even if the current package has uncommitted changes
cargo fix --allow-dirty

Cargo.toml overriding direct and transitive dependencies

[patch.crates-io]
# Patch direct and transitive (from color-to-tui) dependencies on ratatui in order to use:
# * feat(table): enforce line alignment in table render
# v0.22.1-alpha.2
# https://github.com/ratatui-org/ratatui/commit/d2429bc3e44a34197511192dbd215dd32fdf2d9c
ratatui = {git = "https://github.com/ratatui-org/ratatui.git", rev = "b6b2da5"}

Visual Studio Code

Debugging extensions

The CodeLLDB extension should create a run/debug configuration in .vscode/launch.json:

{
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "lldb",
            "request": "launch",
            "name": "Debug",
            "program": "${workspaceFolder}/target/debug/filectrl",
            "args": [],
            "cwd": "${workspaceFolder}"
        }
    ]
}

Tasks

You can execute cargo tasks from within VS Code:

  1. Press: CTRL+Shift+P
  2. Enter "Tasks: Run Task"
  3. Enter "rust:"
  4. Select "Show All Tasks..."

Crates - Frameworks and libraries

Name Description
anyhow Concrete Error type built on std::error::Error
cargo-nextest A next-generation test runner
clap Parse command line arguments
chrono Timezone-aware date and time handling
chrono-tz Companion of chrono that adds timezone data
color-to-tui Parse hex colors to tui::style::Color
copypasta Cross-platform Rust system clipboard library
criterion Statistics-driven benchmarking library
crossterm Cross-platform terminal library (Documentation)
cursive Text User Interface (TUI) library. (Comparison to tui).
dirs-next Low-level library that provides conventional config/cache/data paths
divan Fast and simple benchmarking
egui An easy-to-use immediate mode GUI in Rust that runs on both web and native
env_logger A logging implementation for log which is configured via an environment variable
enum-iterator #[derive(IntoEnumIterato) for enums
gtk-rs GTK4, Cairo, glib, etc bindings
indicatif Progress bar library
itertools Extra iterator adaptors, functions and macros
lazy_static A macro for declaring lazily evaluated statics
mdBook A CLI tool to create books with Markdown
notify Cross-platform filesystem notification library
OnceCell Single assignment cells and lazy values
rand Generate random numbers
ratatui Text User Interface (TUI) library. Successor to tui (ratatui-book)
Serde JSON Serialize and deserialize JSON
strum Various #[derive(...)] for enums
tempfile Create temporary files or directories
tera Template engine inspired by Jinja2
test-case Macro to generate parameterized test cases
textwrap A library for word wrapping text
tokio Async runtime, including IO, networking, scheduling, and timers
uuid Generate and parse UUIDs
winit Cross-platform window creation and management

Software

Name Description
Alacritty A cross-platform, OpenGL terminal emulator
bevy Game engine

Troubleshooting

cargo build
   Compiling space_time_rewind v0.1.0 (/home/andornaut/src/github.com/andornaut/space-time-rewind)
thread 'rustc' panicked at 'failed to lookup `SourceFile` in new context', compiler/rustc_query_impl/src/on_disk_cache.rs:514:22

Fix:

cargo clean && cargo build