- Installation: `cargo install cargo-watch
- Run:
cargo watch -x run -x test -x check - And to watch changes in only the src folder and clear the console, set release mode use:
cargo watch -c -w src -x 'run -r'cargo test -- --show-output
- Installation:
brew install michaeleisel/zld/zld - Configuration: in
.cargo/config.toml
## .cargo/config.toml
## On Windows
## cargo install -f cargo-binutils
## rustup component add llvm-tools-preview
[target.x86_64-pc-windows-msvc]
rustflags = [ "-C", "link-arg=-fuse-ld=lld-link"]
[target.x86_64-pc-windows-gnu]
rustflags = [ "-C", "link-arg=-fuse-ld=lld"]
## On Linux
## - Ubuntu `sudo apt install lld clang`
## - Arch `sudo pacman -S lld clang`
[target.x86_64-unknown-linux-gnu]
rustflags = [ "-C", "linker=clang", "-C", "link-arg=-fuse-ld=lld"]
## On macOS
## - `brew install michaeleisel/zld/zld`
[target.x86_64-apple-darwin]
rustflags = [ "-C", "link-arg=-fuse-ld=/opt/homebrew/bin/zld"]
[target.aarch64-apple-darwin]
rustflags = [ "-C", "link-arg=-fuse-ld=/opt/homebrew/bin/zld"]Rem: May need to install nightly compiler (rustup toolchain install nightly --allow-downgrade
use cargo +nightly expand
- Installation:
cargo install cargo-audit - Run:
cargo audit - Todo: Investigate:
cargo-deny
- Installation:
rustup component add rustfmt - Run: cargo fmt
- CI/CD:
cargo fmt -- --check
- Installation:
rustup component add clippy - Run:
cargo clippy - CD/CI:
cargo clippy -- -D warnings(will fail)
cargo install slint-lspnvimconfiguration: Github
- Installation:
cargo install cargo-tarpaulin - Run:
cargo tarpaulin --ignore-test
- Installation:
cargo install cargo-audit - Run:
cargo audit
- Installation:
cargo install cargo-deny - Initialization project:
cargo deny init - Run:
cargo deny check
- Installation:
cargo install cargo-expand - Run:
cargo expand | more
- Installation:
cargo install cargo-udeps - Run:
cargo udeps
- Installation:
cargo install cargo-chefcheck website for docker setup
- Installation
cargo install cargo-generate - Run:
cargo generate --git https://github.com/<git_repo.git>
RUST_TRACEBACK=1 cargo run
- Installation
cargo install cargo-criteriona. Make sure to havegnuplotinstalled for html files, e.g.,brew install gnuplotb. Have the propercriterion.tomlin theprojectdirectory - Running
cargo criteriona. Create filebenches\my_bench.rs, and updateb. Check thehtmlfile intarget\criterion\reports\index.html`
- With
match
use std::fs::File;
use std::io::ErrorKind;
fn main() {
let greeting_file_result = File::open("hello.txt");
let greeting_file = match greeting_file_result {
Ok(file) => file,
Err(error) => match error.kind() {
ErrorKind::NotFound => match File::create("hello.txt") {
Ok(fc) => fc,
Err(e) => panic!("Problem creating the file: {:?}", e),
},
other_error => {
panic!("Problem opening the file: {:?}", other_error);
}
},
};
}2 . without match
let greeting_file = File::open("hello.txt").unwrap_or_else(|error| {
if error.kind() == ErrorKind::NotFound {
File::create("hello.txt").unwrap_or_else(|error| {
panic!("Problem creating the file: {:?}", error);
})
} else {
panic!("Problem opening the file: {:?}", error);
}
});- Installation:
cargo install cargo-generate - Run:
cargo generate <https://github.coom..> --name <my-project>
let ignore_case = env::var("IGNORE_CASE").is_ok();use IGNORE_CASE=1 cargo run
- Allocate new instance on the heap
- Borrow check verified at compile time
- Sharing ownership by reference counting.
- Similar to a
Boxwith cloning will not allocate new data, just update a stored counter. Rcis not thread safe as the reference count can be updated at the same time. - does not have theSendtraitArcis thread safe - It has theSend(used in move) trait
- Also known as interior mutability
- Borow check verified at RUNTIME (if problem will panic)
- Provide the mutable vs immutable borrowing
CellneedsCopytrait, usingtake()RefCelluses references, usingborrow_mut()
- Prevent data races when updating instance between threads
RwLock<T>allows multiple reads but a single write and thus is more expensive
- Version of
Cellbut limited to U32 or small types<T> - Tool for making sharing between threads possible
SendTrait allows to move ownership to another thread, e.g.,Arc,Cell, primitives likei32,f64SyncTrait allows to shared with another thread, e.g., primitives likei32,f64(butCellis not)- If a structure has all its fields with
SendorSynctraits, the structure will also have the corresponding traits (To avoid usestd::marker::PhantomData<T>withTnot having the trait that is not supposed to be propagated to the structure. e.g.
struct X {
handle: i32,
_not_sync_: std::marker::PhantomData<Cell<()>>,
}
X will have Send trait but not Sync.
-
slint-viewera. Installationcargo install slint-viewerb. Run is fromsrcdir and callslint-viewer ui/main.ui -
Example is
cargo-uia. Installationcargo install cargo-uib. running ascargo-ui -
Crate in github
- Cow (Copy-On-Write) see blog
- anyhow.workspace = true
- async-trait.workspace = true
- chrono.workspace = true
- clap = { version = "4.2.4", features = ["derive"] }
- crossterm = "0.25"
- directories = "5.0.0"
- log.workspace = true
- simplelog = "0.12.1"
- textwrap = "0.16.0"
- thiserror = "1.0.40"
- toml = "0.7.3"
- tui = "0.19.0"
- tui-textarea = "0.2.0"
- actix-web
- tokio = {version = "2", features
- Repaint function with type
Arc<dyn Fn() + Send + Sync + 'static> - User with return value
Fut<Option<User>> - Future
- use
Cow<'a, str>
#![deny(clippy::unwrap_used)]
#![deny(clippy::expect_used)]
#![deny(clippy::panice)]
#!deny(clippy::unused_must_use)]```
### Important Std Traits
`From`, `TryFrom`, `FromStr`
### Limit cloning
- Avoid clone inside constructor (specify if ownership is taken over when using the call)
- In Multithreaded environment when threads use the same data
- For read only: use `Arc::clone(config)`
- For read/write : use `Arc::clone(RwLock::new(config))`
### Use pattern matching
Examples:
1. All cases
```rust
match user {
Some(User{name}) if name.is_empty() => println!("No Name"),
Some(User{name}) => println!("Name: {}", name),
None => println!("No User"),
}- if -> True
match status {
Status::Active | Status::Pending => true,
_ => false,
}or use macro
match!(status, Status::Active | Status::Pending)- Pulling the first element of an array
if let [first, ..] = list {Except with std::prelude::*, Test super::*, Resport all elements in a crate library
HTTP (2012-09-27) Comparison
ActixAxumRocket