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

Top comments (0)