Wasm Builders

Cover image for Standard user input in RustWasm : WebAssembly by example
Ajay Kumar
Ajay Kumar

Posted on • Updated on

Standard user input in RustWasm : WebAssembly by example

In this tutorial I will be discussing about taking standard input from users (i.e. input from keyboard) and standard output (i.e. displaying output on console/terminal). So let's get started and create a project by typing:

cargo new user_input
Enter fullscreen mode Exit fullscreen mode

Navigate to the src folder and start with importing io library. the file will look like so:

use std::io;
fn main() {
    println!("Hello, world!");
}
Enter fullscreen mode Exit fullscreen mode

Now now let's write some code to instruct the user to give standard input and define a variable. Now the file will look like such:

use std::io;fn main() {
    println!("Hello, world!");
    println!("Please Enter Something");

    let mut input = String::new();
}
Enter fullscreen mode Exit fullscreen mode

And finally let's add a few more lines to take standard input, handle error, and display the result. The finalized file is:

use std::io;fn main() {
    println!("Hello, world!");
    println!("Please Enter Something");

    let mut input = String::new();

    io::stdin()
        .read_line(&mut input)
        .expect("Something Went Wrong while reading input");
    println!("\nYour input was: {}", input);
}
Enter fullscreen mode Exit fullscreen mode

Here stdin is used to take standard input and read_line will read the input from keyboard while expect will handle errors if it fails to read the input given by the user.
Now we build this project by performing the following command:

cargo wasi build
Enter fullscreen mode Exit fullscreen mode

Let's run the application:

 

cargo wasi run
Enter fullscreen mode Exit fullscreen mode

Where the cargo-wasi is a subcommand for Cargo which provides a convenient set of defaults for building and running Rust code on the wasm32-wasi target. Please visit this if you haven't installed yet.

The output will be like so:

ajayrmavs33236@rmavs:~/Desktop/WebAssembly-by-Examples-RustWasm/user_input$ cargo wasi build
    Finished dev [unoptimized + debuginfo] target(s) in 0.25s
ajayrmavs33236@rmavs:~/Desktop/WebAssembly-by-Examples-RustWasm/user_input$ cargo wasi run
    Finished dev [unoptimized + debuginfo] target(s) in 0.02s
     Running `/home/ajayrmavs33236/.cargo/bin/cargo-wasi target/wasm32-wasi/debug/user_input.wasm`
     Running `target/wasm32-wasi/debug/user_input.wasm`
Hello, world!
Please Enter Something
this is an example of taking user input of WebAssembly by example series

Your input was: this is an example of taking user input of WebAssembly by example series
Enter fullscreen mode Exit fullscreen mode

Link to previous tutorial can be found here

Discussion (0)