從 Rust 開始入門 WebAssembly


從 Rust 開始入門 WebAssembly | WebAssembly 教程


在上一篇文章裡,我們介紹了 。

現在先從 Rust 開始動手實踐吧。 Rust 是當今編寫 WebAssembly 應用程序的最佳語言。

本文所用到的源代碼Repo請點擊:https://github.com/second-state/wasm-learning/tree/master/rust

雖然 WebAssembly 支持多種編程語言,但迄今為止, Rust 擁有最好的工具。 在過去的4年裡,Rust 被 StackOverflow 用戶評選為最受喜愛的編程語言,是增長最快的編程語言之一。

Rust 像 C 一樣通用和高效,但是由於它的編譯器設計,Rust 比 C 安全得多。 像 C 語言一樣,Rust 有一個學習曲線。 在本教程中,我將幫助您開始使用 Rust 編程語言。你可以通過在線資源,比如這本書瞭解更多有關 Rust 語言的信息。

安裝Rust

在典型的 Linux 系統裡,運行下面的指令安裝 Rust 編譯器和 cargo工具來創建管理。

<code>$ sudo apt-get update
$ sudo apt-get -y upgrade

$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
$ source $HOME/.cargo/env
/<code>

Hello World

此演示應用程序的源代碼可以點擊:https://github.com/second-state/wasm-learning/blob/master/rust/hello.md

首先,讓我們使用 cargo 創建一個新項目。

<code>$ cargo new hello
Created binary (application) `hello` package
$ cd hello
/<code>

在 src/main.rs 中的main () 函數,是執行 Rust 應用程序時的入口點。Src / main. Rs 文件內容如下。該代碼只是將一個字符串“ helloworld”打印到標準輸出。

<code>fn main() {
println!(“Hello, world!”);
}
/<code>

接下來為你的機器創建二進制可執行文件。

<code>$ cargo build --release
Compiling hello v0.1.0 (/home/ubuntu/wasm-learning/rust/hello)
Finished release [optimized] target(s) in 0.22s
/<code>

你現在可以運行你的第一個 Rust 程序並查看 console 上的“Hello World”

<code>$ target/release/hello
Hello, world!
/<code>

互動

這個演示的源代碼可以在這裡找到 https://github.com/second-state/wasm-learning/blob/master/rust/cli.md。

同樣,讓我們使用 cargo 創建一個新項目。

<code>$ cargo new cli
Created binary (application) `cli` package
$ cd cli
/<code>

Src / main.Rs 文件的內容如下。env::args() 會保存我們執行程序時從命令行傳遞的字符串值。 這裡還要注意到,我們先創建一個 Rust 字符串,然後將更多的字符串引用附加給它。 為什麼我們必須連接字符串引用而不是字符串值? 這就是 Rust 讓程序變得安全的原因。 點擊這裡瞭解更多。

<code>use std::env;

fn main() {
let args: Vec<string> = env::args().collect();
println!("{}", String::from("Hello ") + &args[1]);
}
/<string>/<code>

接下來,為你的機器創建二維碼可執行文件。

<code>$ cargo build --release
/<code>

你可以運行程序,並傳入一段命令行代碼

<code>$ target/release/cli Rust
Hello Rust
/<code>

WebAssembly 呢?

現在我們已經瞭解瞭如何從 Rust 源代碼創建本地可執行的程序。 可執行的程序只能在生成計算機上運行,可能不安全。 在接下來的教程中,將展示:

  • 如何從 Rust 源代碼構建 WebAssembly 字節碼程序而不是本地可執行文件。
  • 如何通過 web 瀏覽器而不是繁瑣的命令行與 WebAssembly 程序進行交互。

相關閱讀


分享到:


相關文章: