Standard user input in RustWasm : WebAssembly by example

Standard user input in RustWasm : WebAssembly by example

·

2 min read

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 start a project by typing -

cargo new user_input

and 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!");
}

Now now let's write some code to instruct 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();
}

and finally let's add few more line to take standard input and handle error if occered and then display the same, nowand the finalized file :

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);
}

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

cargo wasi build

and to run the project perform command

cargo wasi run

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.visit this if you haven't installed. 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

I used to Publish my Rust WebAssembly tutorial at wasm.builders and others technical and non-technical tutorial over here on Hashnode itself, feel free to have read those too. Thank You. Link to previous WebAssembly tutorial can be found here

Did you find this article valuable?

Support Ajay Kumar by becoming a sponsor. Any amount is appreciated!