你還不知道的 Rust10 個小技巧(下)
0x00 開篇
Rust 是一種很棒的編程語言:可靠、快速,但是也相當複雜,學習曲線相對來說比較陡峭。今天給大家介紹下 Rust 的 10 個小技巧剩餘的 5 個小技巧。
0x01 自定義並鏈接 Panic handlers
Panic Handler(通常也被稱爲 hooks)可以被重寫和鏈接,這在爲應用程序設置自定義錯誤報告和日誌記錄時會很有用。示例代碼如下:
use std::panic::{set_hook, take_hook};
fn main() {
let prev_hook = take_hook();
set_hook(Box::new(move |panic| {
println!("custom logging logic {}", panic);
prev_hook(panic);
}));
let prev_hook = take_hook();
set_hook(Box::new(move |panic| {
println!("custom error reporting logic {}", panic);
prev_hook(panic);
}));
panic!("test")
}
代碼運行結果:
custom error reporting logic panicked at 'test', src/main.rs:20:5
custom logging logic panicked at 'test', src/main.rs:20:5
0x02 使用閉包時使用 impl Trait
儘可能的使用 impl Fn/FnOnce/FnMut 來將閉包傳遞給函數(impl Trait)來保證簽名的乾淨,而不是使用泛型。對於非正常的情況,你可能需要使用 Box<Fn()> 裝箱,但是可能將會耗費額外的內存開銷。示例代碼如下:
fn setup_teardown_generic<A: FnOnce()>(action: A) {
println!("setting up...");
action();
println!("tearing down...")
}
fn setup_teardown(action: impl FnOnce()) {
println!("setting up...");
action();
println!("tearing down...")
}
fn main() {
setup_teardown(|| {
println!("Action!");
})
}
0x03 在 VSCode 中使用 cargo clippy 來 lint
如果你使用的是 VSCode + Rust Analyzer 來編寫 Rust,我建議你使用cargo clippy
來代替cargo check
你進入 Rust Analyzer > Check On Save:Command,將check
改爲clippy
。設備方法如下:
0x04 與 C/C++ 代碼集成
如果你的 Rust 代碼要與 C/C++ 代碼集成,推薦你使用這個庫cc crate
。它是一個將 C/C++/Assembly 編譯爲 Rust 的 crate 或者 app。示例代碼如下:
// build.rs
// 將`foo.c`和`bar.c`編譯爲 `libfoo.a`
fn main() {
cc::Build::new()
.file("foo.c")
.file("bar.c")
.compile("foo");
}
下面是foo.c
和bar.c
的內容
void foo_function(void) { ... }
int32_t bar_function(int32_t x) { ... }
可以在 Rust 中使用:
extern {
fn foo_function();
fn bar_function(x: i32) -> i32;
}
pub fn call() {
unsafe {
foo_function();
bar_function(42);
}
}
fn main() {
call();
}
0x05 使用 Cargo-Make 來打包
Build Script 適用於很多事情,但通常不適用於打包。本人比較推薦的解決方案是 Sagiegurari 大神的的 Cargo Make,一個基於 Rust 的任務運行器和構建工具。
0x06 部分工具地址
-
Panic Handler:https://doc.rust-lang.org/std/panic/fn.set_hook.html
-
Crossbeam Github:https://github.com/crossbeam-rs/crossbeam
-
Cargo-Make Github:https://github.com/sagiegurari/cargo-make
-
scopeguard crate :https://docs.rs/scopeguard/latest/scopeguard/
-
cc crate:https://crates.io/crates/cc
-
Cargo-Make Github:https://github.com/sagiegurari/cargo-make
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/KvFdIXEptYQFdHx3zuzn4w