只需 5 分鐘,教你如何編寫並執行一個 Rust + WebAssembly 程序


只需 5 分鐘,教你如何編寫並執行一個 Rust + WebAssembly 程序


在探討 WASM 在服務端的巨大潛力時,我們提到 WASM 的一大優勢就是支持有影響力的新銳編程語言,例如 Rust 。這篇文章將展示如何編寫並執行一個 Rust + WebAssembly 程序,只有代碼。

本文作者: Second State 的研究員、開源核心開發 Tim McCallum。

該演示是使用 Ubuntu Linux 操作系統和 Google 的 Chrome 瀏覽器進行的。其他組合尚未經過測試。


只需 5 分鐘,教你如何編寫並執行一個 Rust + WebAssembly 程序


第1步:安裝 Apache2 和 Rust

運行以下所有 Ubuntu 系統設置命令(更新,安裝 Apache2 和 Rust )

sudo apt-get update
sudo apt-get -y upgrade
sudo apt-get -y install apache2
sudo chown -R $USER:$USER /var/www/html
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env
rustup target add wasm32-wasi
rustup override set nightly

第2步:創建一個新的 Rust 項目

創建一個快速的 Rust 項目

cd ~
cargo new --lib triple
cd triple

第3步:為 Wasm 配置 Rust

通過將下面的配置添加到 〜/ triple / Cargo.toml 文件的 lib 部分來配置 rust

[lib]
name = "triple_lib"
path = "src/triple.rs"
crate-type =["cdylib"]

第4步:指定構建目標

通過在 〜/ .cargo.config 中創建一個新文件並添加以下配置來完成 Rust 的配置

[build] 

target = "wasm32-wasi"

第5步:寫 Rust

編寫一個快速的 Rust 程序並將其保存為 Triple.rs(在 〜/ triple / src 目錄中)

#[no_mangle]
pub extern fn triple(x: i32) -> i32 {
return 3 * x;
}

第6步:構建 Wasm 代碼

將 Rust 代碼構建到 Wasm 中,然後將 Wasm 文件複製到 Apache2 Web 服務器區域

cd ~/triple
cargo build - release
cp -rp ~/triple/target/wasm32-wasi/release/triple_lib.wasm /var/www/html/triple.wasm

第7步:製作 HTML 網頁

在 var / www / html / 目錄中創建一個名為 Triple.html 的新文件,並使用以下代碼填充它。


\t
\t\t<link>
\t\t
\t
\t
\t\t

\t\t\t

\t\t\t

\t\t\t\tRust to Wasm in under 5 minutes - Triple the number
\t\t\t

\t\t\t

\t\t

\t\t

\t\t

\t\t\t

\t\t\t
Place a number in the box

\t\t\t
Click the button

\t\t\t

\t\t

\t\t

\t\t\t

\t\t\t

\t\t\t\t
\t\t\t\t

\t\t\t\t

\t\t\t\t\t<button>Triple the number/<button>
\t\t\t\t

\t\t\t\t

\t\t\t

\t\t
\t\t
\t

第8步:單擊鼠標執行寫好的 Rust 代碼

在 triple HTML 頁面:http://12.345.456.78/triple.html 上訪問計算機的IP。

然後單擊 “Triple the number” 按鈕。


只需 5 分鐘,教你如何編寫並執行一個 Rust + WebAssembly 程序


將顯示以下提示。


只需 5 分鐘,教你如何編寫並執行一個 Rust + WebAssembly 程序

如圖所示:8的三倍等於24


到這裡我們就完成了一個Rust + WebAssembly 程序,你也來試試吧!


作者:Tim McCallum
鏈接:https://juejin.im/post/5de62000e51d4557f852a141


分享到:


相關文章: