你不知道的 Rust

前言
本文档不是一篇Rust入门教程,而是从前端开发者的视角对Rust进行较感性的杂谈:诸如学习曲线、开发体验、语法差异、性能差异、优势领域等细节会被讨论到。通过这种横向的对比,有助于我们进一步了解:
我们是否需要去学习Rust,学习它大概需要的时间成本
Rust开发体验有哪些痛点,又有那些爽点
Rust在不同场景的具体优势在哪里
我们前端开发者可以基于Rust做哪些有意思的东西
学习曲线


这里选取几个较有代表性的语言作为比较对象,分别对入门和精通两个场景进行一个简单对比:
入门

标准:以完成一个简单demo作为入门标准
结论:Rust >> C++ > C > TypeScript > JavaScript
细节:
我们知道Rust以编译器严格著称,在你成功跑起一个诸如《猜数游戏》[1]的demo之前,你需要经历编译器在编码阶段和编译阶段的双重吊打(严格的语法、Rust特有的ownership[2]规则、生命周期等);另外还需要消化一些较新颖的语法如match匹配模式[3]、Option/Result[4],这会是漫长且痛苦的一段时间。
即便是难如C++也会在入门阶段允许你较快地编写出一个可运行的demo,而基于Rust的设计理念[5],这个难度从你开始写的第一行代码就需要背负。但即便如此,开发者在多次编译器报错中会开始逐渐适应Rust的规则和细节,当迈过这个坎后,编码的速度会有明显的提升,恭喜此时已越过Rust第一个也是最陡峭的山坡。
精通

标准:以熟练掌握语言的高阶功能和最佳实践作为精通标准
结论:C++ ≈ Rust >> TypeScript > C > JavaScript
细节:
如传闻所言:“没有人可以精通C++,包括Bjarne Stroustrup本人”,虽然有夸大成分,但当中的复杂内容:宏、多范式编程、函数重载、手动管理内存、线程默认不安全、指针的高效使用等确实足以让程序员花费数年甚至数十年去完全掌握这门语言
相较于C++,精通Rust的难度个人感觉丝毫不减,一些共同的难点包括:宏、多范式编程、函数重载,指针的高效使用;虽然Rust的ownership规则优秀地实现了减少了线程安全以及手动管理内存的心智负担,但新引入的生命周期lifetime[6]、trait语法[7]、切片[8]等概念也是Rust劝退的首席代表
开发细节(Pros & Cons)

下面将通过对比一些在TypeScript/JavaScript中常用到的语法、数据结构和设计模式在Rust实现的异同,来感受它们具体的开发细节差异:
Cons

字符串操作

ts/js的字符串拼接非常便捷,而Rust虽然方法比较多但相对还是比较繁琐的:
const a = "Hello";
const b = "world";
// 1. ``
console.log(`${a},${b}`); // 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
重复代码

通过一定的抽象,我们在ts/js基本上可以做到不重复地写如下代码,但目前在Rust原生层面还是未能很好地支持:
enum的值问题

一般使用中我们会把enum的每个item绑定一个值,比如说enum是请求返回的一个字段,那么值的对应的是服务端具体对应字段的数字
enum AllotStatus {
  unknown = 0,
  /** 待分配 */
  wait_allot = 1,
  /** 待挑选 */
  wait_pitch = 2,
  /** 全部 */
  all_status = 3,
}
由于Rust的enum是没有“值”的概念的,因此如果你想把enum的每个item映射到一个具体的值需要这样实现:
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写法中出现了6次AllotStatus这个单词,
stackoverflow[9]上也有一个类似的讨论以供参考
可选函数变量及默认值

我们在JavaScript/TypeScript可以轻松将某几个函数参数设置为可选的,并且为它们提供一个默认值,而这在Rust是暂时还不支持的:
function merge(a: string, b?: string, options = 'test') {}
fn add(a: String, b: Option<String>, c: Option<String>) {
    // 需要在函数开头显示赋值一次
    let b = b.unwrap_or("");
    let c = c.unwrap_or("test");
}
闭包

基于Rust对于闭包较严格的要求,以下这段基于JavaScript/TypeScirpt的递归遍历收集文件路径的代码在Rust实现起来并没有那么轻松:
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实现大概样子是这样的:
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这个函数在闭包中并没有被申明

// 因此一种妥协的写法是:
// 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);
更多相关的说明可以查看这里[10]和这里[11]
Pros

match匹配模式

Rust的招牌match匹配模式在进行匹配模式判断的时候比JavaScript/TypeScirpt的switch句式要优越不少,下面是具体的例子,根据字符串s的内容做匹配:
let res = match s {
  "i32" => IdlFieldType::Number,
  "i64" | "string" => IdlFieldType::String, // 或语句
  // 匹配项还可以是一个函数式,比如这里的正则匹配,非常灵活
  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通过在函数结尾添加?(question mark)的语法糖来节省多次编写对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方案,在一些适合并发场景(比如把上述场景扩展到读取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') //必须是网络路径,不能是本地路径
worker.postMessage('Hello World')
worker.postMessage({method: 'echo', args: ['Work']})
worker.onmessage = function (event) {
  console.log('Received message ' + event.data)
  // worker.terminate()  // 结束web worker 释放资源
}

// 子线程
var self = this
self.addEventListener('message', function (e) {
  self.postMessage('You said: ' + e.data)
}, false)
单测

JavaScript/TypeScript

在前端一般我们需要借助Jest等测试框架来运行单测文件,有如下特点:
需要安装Jest框架
单测文件一般单独写在一个单测文件,与原文件有一定的割裂感
运行单测以命令行形式运行

Rust

Rust单测相较来说有一下优点:
Rust内置单测功能无需安装第三方包
单测代码一般和被测代码写在同一个文件
编辑器内置了单个单测运行按钮,方便了对单测的及时验证


性能

以下数据非严格实验条件下的精准数据,仅作为性能数量级的一个感官对比参考
对比场景

遍历一个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做了较多性能优化,使得node的文件遍历性能不算太差
Rust    1.5s    时间大概是node的46%
在一些适合多线程的场景,Rust凸显的优势会更加明显(比如把上述场景扩展到读取10个互相独立的node_modules文件夹),在上面的 “多线程” 已有介绍
应用场景

工具方向

编译打包相关:
前端代码编译&打包
https://swc.rs/
SWC
代码转义:
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 函数重写为 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开发
https://www.warp.dev/
Wrap
其他

Linux内核/嵌入式开发
https://github.com/Rust-for-Linux
学习资料

Rust的入门教程个人比较建议直接跟随官方入门书[12]以及辅助参考《Rust语言圣经》[13]
另外可以多参考上面提到的一些小型的Rust工具库[14]的源码,代码量较小容易入门
参考资料
[1]
《猜数游戏》: 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]
设计理念: 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语言圣经》: https://rusty.rs/
[14]
工具库: https://github.com/justjavac/postcss-rs





作者:ELab.liukaizhan


欢迎关注微信公众号 :前端民工