你不知道的 Rust
前言
本文檔不是一篇Rust入門教程,而是從前端開發(fā)者的視角對Rust進行較感性的雜談:諸如學(xué)習(xí)曲線、開發(fā)體驗、語法差異、性能差異、優(yōu)勢領(lǐng)域等細(xì)節(jié)會被討論到。通過這種橫向的對比,有助于我們進一步了解:
我們是否需要去學(xué)習(xí)Rust,學(xué)習(xí)它大概需要的時間成本
Rust開發(fā)體驗有哪些痛點,又有那些爽點
Rust在不同場景的具體優(yōu)勢在哪里
我們前端開發(fā)者可以基于Rust做哪些有意思的東西
學(xué)習(xí)曲線
這里選取幾個較有代表性的語言作為比較對象,分別對入門和精通兩個場景進行一個簡單對比:
入門
標(biāo)準(zhǔn):以完成一個簡單demo作為入門標(biāo)準(zhǔn)
結(jié)論:Rust >> C++ > C > TypeScript > JavaScript
細(xì)節(jié):
我們知道Rust以編譯器嚴(yán)格著稱,在你成功跑起一個諸如《猜數(shù)游戲》[1]的demo之前,你需要經(jīng)歷編譯器在編碼階段和編譯階段的雙重吊打(嚴(yán)格的語法、Rust特有的ownership[2]規(guī)則、生命周期等);另外還需要消化一些較新穎的語法如match匹配模式[3]、Option/Result[4],這會是漫長且痛苦的一段時間。
即便是難如C++也會在入門階段允許你較快地編寫出一個可運行的demo,而基于Rust的設(shè)計理念[5],這個難度從你開始寫的第一行代碼就需要背負(fù)。但即便如此,開發(fā)者在多次編譯器報錯中會開始逐漸適應(yīng)Rust的規(guī)則和細(xì)節(jié),當(dāng)邁過這個坎后,編碼的速度會有明顯的提升,恭喜此時已越過Rust第一個也是最陡峭的山坡。
精通
標(biāo)準(zhǔn):以熟練掌握語言的高階功能和最佳實踐作為精通標(biāo)準(zhǔn)
結(jié)論:C++ ≈ Rust >> TypeScript > C > JavaScript
細(xì)節(jié):
如傳聞所言:“沒有人可以精通C++,包括Bjarne Stroustrup本人”,雖然有夸大成分,但當(dāng)中的復(fù)雜內(nèi)容:宏、多范式編程、函數(shù)重載、手動管理內(nèi)存、線程默認(rèn)不安全、指針的高效使用等確實足以讓程序員花費數(shù)年甚至數(shù)十年去完全掌握這門語言
相較于C++,精通Rust的難度個人感覺絲毫不減,一些共同的難點包括:宏、多范式編程、函數(shù)重載,指針的高效使用;雖然Rust的ownership規(guī)則優(yōu)秀地實現(xiàn)了減少了線程安全以及手動管理內(nèi)存的心智負(fù)擔(dān),但新引入的生命周期lifetime[6]、trait語法[7]、切片[8]等概念也是Rust勸退的首席代表
開發(fā)細(xì)節(jié)(Pros & Cons)
下面將通過對比一些在TypeScript/JavaScript中常用到的語法、數(shù)據(jù)結(jié)構(gòu)和設(shè)計模式在Rust實現(xiàn)的異同,來感受它們具體的開發(fā)細(xì)節(jié)差異:
Cons
字符串操作
ts/js的字符串拼接非常便捷,而Rust雖然方法比較多但相對還是比較繁瑣的:
const a = "Hello";
const b = "world";
// 1. ``
console.log(`${a},$`); // good
// 2. +
console.log(a + ',' + b);
// 3. join
[a, b].join(',');
let mut _a = "Hello".to_string();
let _b = "world".to_string();
// 1. push_str
_a.push_str()
_a.push_str(&_b);
println!("{}", _a);
// 2. +
println!("{}", _a + ",".to_string() + &_b);
// 3. !format
println!("{}", format!("{},{}", _a, _b)); // not bad
// 4. !concat
println!("{}", concat!("a", "b"));
https://stackoverflow.com/questions/30154541/how-do-i-concatenate-strings
重復(fù)代碼
通過一定的抽象,我們在ts/js基本上可以做到不重復(fù)地寫如下代碼,但目前在Rust原生層面還是未能很好地支持:
enum的值問題
一般使用中我們會把enum的每個item綁定一個值,比如說enum是請求返回的一個字段,那么值的對應(yīng)的是服務(wù)端具體對應(yīng)字段的數(shù)字
enum AllotStatus {
unknown = 0,
/** 待分配 */
wait_allot = 1,
/** 待挑選 */
wait_pitch = 2,
/** 全部 */
all_status = 3,
}
由于Rust的enum是沒有“值”的概念的,因此如果你想把enum的每個item映射到一個具體的值需要這樣實現(xiàn):
pub enum AllotStatus {
Unknown,
WaitAllot,
WaitPitch,
AllStatus,
}
impl Code for AllotStatus {
fn fmt(&self) -> Result {
match self {
&AllotStatus::Unknown => 0,
&AllotStatus::WaitAllot => 1,
&AllotStatus::WaitPitch => 2,
&AllotStatus::AllStatus => 2,
}
}
}
我們可以看到Rust寫法中出現(xiàn)了6次AllotStatus這個單詞,
stackoverflow[9]上也有一個類似的討論以供參考
可選函數(shù)變量及默認(rèn)值
我們在JavaScript/TypeScript可以輕松將某幾個函數(shù)參數(shù)設(shè)置為可選的,并且為它們提供一個默認(rèn)值,而這在Rust是暫時還不支持的:
function merge(a: string, b?: string, options = 'test') {}
fn add(a: String, b: Option<String>, c: Option<String>) {
// 需要在函數(shù)開頭顯示賦值一次
let b = b.unwrap_or("");
let c = c.unwrap_or("test");
}
閉包
基于Rust對于閉包較嚴(yán)格的要求,以下這段基于JavaScript/TypeScirpt的遞歸遍歷收集文件路徑的代碼在Rust實現(xiàn)起來并沒有那么輕松:
const names = [];
function travel(folderPath = '') {
const subNames = fs.readdirSync(dirPath);
for (const subName of subNames) {
const subPath = path.resolve(dirPath, subName);
const status = fs.lstatSync(subPath);
const isDir = status.isDirectory();
if (isDir) {
travelFolder(subPath);
} else {
names.push(subPath);
}
}
}
// 上述代碼在Rust實現(xiàn)大概樣子是這樣的:
let names: Vec<String>;
let travel = |path: u32| {
let paths = read_dir(path).unwrap();
for path in paths {
let path = path.unwrap().path();
if meta.is_dir() {
travel(path);
} else {
names.push(String::from(path));
}
}
};
// 這里編譯器會報錯`cannot find function `travel` in this scope not found in this scope`
// 原因是travel這個函數(shù)在閉包中并沒有被申明
// 因此一種妥協(xié)的寫法是:
// see https://stackoverflow.com/questions/30559073/cannot-borrow-captured-outer-variable-in-an-fn-closure-as-mutable about why using `Arc` and `Mutex`
let mut res = Arc::new(Mutex::new(Vec::<String>::new()));
struct Iter<'s> {
f: &'s dyn Fn(&Iter, &str) -> (),
}
let iter = Iter {
f: &|iter, path| {
let paths = read_dir(path).unwrap();
for path in paths {
let path = path.unwrap().path();
let meta = metadata(path.clone()).unwrap();
let path = path.to_str().unwrap();
if meta.is_dir() {
(iter.f)(iter, path);
} else {
res.lock().unwrap().push(String::from(path));
}
}
},
};
(iter.f)(&iter, folder_path);
更多相關(guān)的說明可以查看這里[10]和這里[11]
Pros
match匹配模式
Rust的招牌match匹配模式在進行匹配模式判斷的時候比JavaScript/TypeScirpt的switch句式要優(yōu)越不少,下面是具體的例子,根據(jù)字符串s的內(nèi)容做匹配:
let res = match s {
"i32" => IdlFieldType::Number,
"i64" | "string" => IdlFieldType::String, // 或語句
// 匹配項還可以是一個函數(shù)式,比如這里的正則匹配,非常靈活
s if Regex::new(r"refers?").unwrap().is_match(s) => {}
}
switch(s) {
case 'i32': {
break;
}
case 'i64':
case 'string': {
break;
}
default: {
if (/refers?/.test(s)) {}
break;
}
}
傳播錯誤捷徑——?
Rust通過在函數(shù)結(jié)尾添加?(question mark)的語法糖來節(jié)省多次編寫對result的錯誤判斷處理
// long way without using question mark operator ?
fn find_char_index_in_first_word() {
let res1 = func1()?;
let res2 = func2()?;
}
function find_char_index_in_first_word() {
const res1 = func1();
if (!res1) {
return xxx;
}
const res2 = func2();
if (!res2) {
return xxx;
}
}
多線程
基于rust的多線程thread方案,在一些適合并發(fā)場景(比如把上述場景擴展到讀取10個互相獨立的node_modules文件夾),則可以進一步加速程序,相較于js使用web worker(相對割裂的方案)可能會是一個更合適的方案
use std::thread;
use std::time::Duration;
fn main() {
thread::spawn(|| {
for i in 1..10 {
println!("hi number {} from the spawned thread!", i);
thread::sleep(Duration::from_millis(1));
}
});
for i in 1..5 {
println!("hi number {} from the main thread!", i);
thread::sleep(Duration::from_millis(1));
}
}
// 主線程
var worker = new Worker('/jsteststatic/static/worker.js') //必須是網(wǎng)絡(luò)路徑,不能是本地路徑
worker.postMessage('Hello World')
worker.postMessage({method: 'echo', args: ['Work']})
worker.onmessage = function (event) {
console.log('Received message ' + event.data)
// worker.terminate() // 結(jié)束web worker 釋放資源
}
// 子線程
var self = this
self.addEventListener('message', function (e) {
self.postMessage('You said: ' + e.data)
}, false)
單測
JavaScript/TypeScript
在前端一般我們需要借助Jest等測試框架來運行單測文件,有如下特點:
需要安裝Jest框架
單測文件一般單獨寫在一個單測文件,與原文件有一定的割裂感
運行單測以命令行形式運行
Rust
Rust單測相較來說有一下優(yōu)點:
Rust內(nèi)置單測功能無需安裝第三方包
單測代碼一般和被測代碼寫在同一個文件
編輯器內(nèi)置了單個單測運行按鈕,方便了對單測的及時驗證
性能
以下數(shù)據(jù)非嚴(yán)格實驗條件下的精準(zhǔn)數(shù)據(jù),僅作為性能數(shù)量級的一個感官對比參考
對比場景
遍歷一個node_modules文件夾下的所有文件夾的路徑(大概28000個文件)
對比方案
NodeJS版本
const stack = [];
while (stack.length) {
const cur = stack.pop();
const subNames = fs.readdirSync(cur);
for (const subName of subNames) {
const subPath = path.resolve(cur, subName);
const status = fs.lstatSync(subPath);
const isDir = status.isDirectory();
if (isDir) {
stack.push(subPath);
}
// ...
}
}
Rust版本
let mut stack: Vec<ReadDir> = vec![root];
while !stack.is_empty() {
let cur = stack.pop().unwrap();
for r in cur {
let path = r.unwrap().path();
if path.is_dir() {
let p = read_dir(path).unwrap();
stack.push(p);
}
// ...
}
}
方案 平均運行時間(5次平均) 備注
NodeJS 3.2s v8做了較多性能優(yōu)化,使得node的文件遍歷性能不算太差
Rust 1.5s 時間大概是node的46%
在一些適合多線程的場景,Rust凸顯的優(yōu)勢會更加明顯(比如把上述場景擴展到讀取10個互相獨立的node_modules文件夾),在上面的 “多線程” 已有介紹
應(yīng)用場景
工具方向
編譯打包相關(guān):
前端代碼編譯&打包
https://swc.rs/
SWC
代碼轉(zhuǎn)義:
Fast and 100% API compatible postcss replacer
https://github.com/justjavac/postcss-rs
thrift idl -> ts types
Ridl:
postcss:
webassembly
Deno
deno目前全面采用rust編寫核心部分
https://deno.land/
ZapLib
通過將速度很慢的 JavaScript 函數(shù)重寫為 Rust 并將它們編譯為 Wasm
https://zaplib.com/
Photon
借助rust+wasm的圖像處理庫
https://github.com/silvia-odwyer/photon
客戶端
Tauri
跨端桌面客戶端
https://github.com/tauri-apps/tauri
dioxus
跨全端
類tsx寫法
https://github.com/DioxusLabs/dioxus
命令行
目前很火的mac端命令行工具,基于Rust開發(fā)
https://www.warp.dev/
Wrap
其他
Linux內(nèi)核/嵌入式開發(fā)
https://github.com/Rust-for-Linux
學(xué)習(xí)資料
Rust的入門教程個人比較建議直接跟隨官方入門書[12]以及輔助參考《Rust語言圣經(jīng)》[13]
另外可以多參考上面提到的一些小型的Rust工具庫[14]的源碼,代碼量較小容易入門
參考資料
[1]
《猜數(shù)游戲》: https://www.bilibili.com/video/BV1hp4y1k7SV?p=8
[2]
ownership: https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html
[3]
match匹配模式: https://doc.rust-lang.org/book/ch06-00-enums.html
[4]
Option/Result: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html?highlight=result#recoverable-errors-with-result
[5]
設(shè)計理念: https://rustacean-principles.netlify.app/how_rust_empowers.html
[6]
生命周期lifetime: https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html#validating-references-with-lifetimes
[7]
trait語法: https://doc.rust-lang.org/book/ch10-02-traits.html#traits-defining-shared-behavior
[8]
切片: https://course.rs/difficulties/slice.html
[9]
stackoverflow: https://stackoverflow.com/questions/36928569/how-can-i-create-enums-with-constant-values-in-rust
[10]
這里: https://stackoverflow.com/questions/16946888/is-it-possible-to-make-a-recursive-closure-in-rust
[11]
這里: http://smallcultfollowing.com/babysteps/blog/2013/04/30/the-case-of-the-recurring-closure/
[12]
官方入門書: https://doc.rust-lang.org/book/title-page.html
[13]
《Rust語言圣經(jīng)》: https://rusty.rs/
[14]
工具庫: https://github.com/justjavac/postcss-rs
作者:ELab.liukaizhan
歡迎關(guān)注微信公眾號 :前端民工