Hello World with Rust and Webassembly

A WASM-code possible to write different ways. Exist excelent application EMScripten that convert  code from C++ or Rust to WASM, but in Rust enviroment possible convert Rust-code with help wasm32-unknown-unknown compiler. 

In this Article I'll show simple example "Hello World" on the Rust and how to run this code with help Flask webframework.

cargo init

change file Cargo.toml

name = "helloworld"
version = "0.1.0"
authors = ["Your Name <info@arahna.de>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

crate-type = ["cdylib"]

wasm-bindgen = "0.2"

Writing a code in file src/lib.rs:

use wasm_bindgen::prelude::*;

// take two integer values and return a + b
pub fn call_me_from_javascript(a: i32, b: i32) -> i32 {
  return a + b;

extern "C" {
    fn alert(s: &str);

// js alert
pub fn alert_window() {
    alert("Hello World!");

Run command in terminal:

wasm-pack build --target web

this command creates a folder pkg, essentially this folder destined for creating node-application, but I won’t use node-app, I’ll using python micro framework Flask. So, we create Flask-app with the following structure:


  - __init__.py

  - hello.py










helloworld.js and helloworld_bg.wasm files from folder pkg

the file index.js will be like this:

import init from "/static/js/helloworld.js";

const runWasm = async () => {

  const helloWorld = await init("/static/wasm/helloworld_bg.wasm");

  const Result_1 = helloWorld.call_me_from_javascript(9, 2);
  const Result_2 = helloWorld.alert_window();
  var div_1 = document.getElementById("1");

  div_1.textContent = Result_1;



<!DOCTYPE html>
    <meta charset="UTF-8" />
    <title>Hello World - Rust</title>
  <div id="1"></div>
  <div id="2"></div>
<script type="module" src="/static/js/index.js"></script>


from flask import Flask
from flask import render_template

app = Flask(__name__)

def hello():
    return render_template('index.html')

if __name__ == "__main__":

run the flask application and look at the page

and on the page number 11

The number 11 is obtained because we call the wasm function from javascript call_me_from_javascript() and pass two values to this function 9 and 2. WASM function adds these two values and returns the result 11. This is very convenient when you need to get the result of complex calculations, which can slow down the site, in such case the task of computing can be assigned to WASM.


Post your comment

Popular Posts