9

rust wasm 记录

 3 years ago
source link: https://zhuanlan.zhihu.com/p/393980151
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

rust wasm 记录

✅趴在床上娇喘,❎隔着网线叫唤

最近一直在研究 swc 和其他的一些 rust 项目,rust 的编译失败率远远大于 go,我也很绝望

why wasm?

实际上,wasm 并不快,可以把它理解为一个阉割版的 vm,同样的 go 跑到 wasm 上大约要慢五倍,rust 稍微好一点点,但也慢得多

所以,如果你企图使用 wasm 解决一些密集计算的性能,还是别想了……

但是 wasm 对我个人而言有一个很重要的功能,那就是替代 ffi,替代 napi

rust wasm

我对 go 更熟悉,go 的 wasm 也非常简单好用,但……很明显前端er更喜欢 rust,对我来说,不管是 go 还是 rust,我写起来都像 js

  1. 全局安装 wasm-pack
cargo install wasm-pack --no-default-features # 忽略 OpenSSL

2. 写 demo

extern crate wasm_bindgen;

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
extern {
    pub fn alert(s: &str);
}

#[wasm_bindgen]
pub fn greet(name: &str) {
    alert(&format!("Hello, {}!", name));
}

编译,target 选 web

wasm-pack build --target web

在浏览器中调用

import('./hello_wasm').then(async m => {
    await m.default()
    m.greet('hello')
})

3. 再写一个 demo

extern crate wasm_bindgen;

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn greet(name: &str) -> String {
    return format!("Hello, {}!", name);
}

编译,target 选 nodejs

wasm-pack build --target nodejs
require('./hello_wasm.js').greet('132')

以上,基本上 rust 写 wasm 就这样了,虽说看上去很简单,但其实编译第三方库失败率还是很高的

总结

之前说的 web 和 js 已经没什么事情可以做了,其实我觉得吧,技术这玩意就是随波逐流,大家在做什么事,我们就应该趁机做同样的事

五年前,vdom 很火,每一个框架作者都将 vdom 移植到自己的框架里

五年后,vdom 被玩烂了,大家重新回归编译路线,这个时候你还在搞 runtime 就很不合时宜

同样的道理,现在大家都在研究 esbuild,swc 这类新工具的时候,过了这个村就没这个包子店了!

当然每个人的经验不一样,所以同样的工具,大家的解法也不同


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK