Hello World on the web

You already saw the "Hello World of WebAssembly" earlier. You will now run this on the web without additional tools.

✅ Create a new crate

cargo new --lib hello-world
cd hello-world

✅ Set the crate type to cdylib in Cargo.toml

[lib]
crate-type = ["cdylib"]

✅ Write the add function.

#[no_mangle]
pub extern "C" fn add(left: i32, right: i32) -> i32 {
    left + right
}

The no_mangle attribute ensures that the function name lands in the binary as is, otherwise you couldn't later call it by name. extern "C" ensures it uses the C-compatible ABI, and thus what WebAssembly (and JavaScript) expects.

✅ Compile it to WebAssembly.

cargo build --target wasm32-unknown-unknown

This will create target/wasm32-unknown-unknown/debug/hello_world.wasm.

✅ Next create an HTML file index.html in your crate's directory (next to Cargo.toml):

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Rust WASM Demo</title>
  </head>
  <body>
    <script type="module">
      <!-- to be filled in -->
    </script>
  </body>
</html>

✅ Now you need to load, compile and instantiate the WebAssembly module. All of this is part of the web API. fetch can load data from URLs, WebAssembly.instantiate() compiles and instantiates the WebAssembly module.

      let response = await fetch('target/wasm32-unknown-unknown/debug/hello_world.wasm');
      let bytes = await response.arrayBuffer();
      let result = await WebAssembly.instantiate(bytes, {});

The result of this is an instance that has accessors for the exported functions of the module.

✅ Call the add method on the Wasm module instance.

      const sum = result.instance.exports.add(1, 2);
      console.log(`1 + 2 = ${sum}`);

✅ Serve your HTML file and the WebAssembly over HTTP.

http

Open http://localhost:8000 in your web browser and open the Developer Tools. In the console you should now see the result:

1 + 2 = 3