Wasm Builders 🧱

Cover image for Rust Module in Rustwasm
Ajay Kumar
Ajay Kumar

Posted on • Updated on

Rust Module in Rustwasm

Module

A logical group of code is called a Module. Multiple modules are compiled into a unit called Crate, where Crate is a compilation unit in Rust.
Module in Rust are private by default.

Declaration Syntax

mod private_module{

    fn private_module_private_function(){
        println!("private_module_private_function get called\n");
    }
    pub fn private_module_public_function(){
        private_module_private_function();
        println!("private_module_public_function get called\n");
    }
}

pub mod public_module{

    fn public_module_private_function(){
        println!("public_module_private_function get called\n");
    }
    pub fn public_module_public_function(){
        public_module_private_function();
        println!("public_module_public_function get called\n");
    }
}
Enter fullscreen mode Exit fullscreen mode

Syntax for accessing Module's functions
In Rust a Module can be private or public, similarly functions inside those modules also can be private and public as shown in Declaration, while private functions can only be accessed by a public function which belongs to the same module. Accessing Syntax would be:

  • Method I of accessing functions
println!("Calling public Modules functions");
public_module_public_function();
println!("Calling Private Modules Functions");
private_module_public_function();
Enter fullscreen mode Exit fullscreen mode
  • Method II of accessing functions
println!("Calling public Modules functions");
public_module::public_module_public_function();
println!("Calling Private Modules Functions");
private_module::private_module_public_function();
Enter fullscreen mode Exit fullscreen mode

Commands to be performed

  • Project creation
cargo new --bin rust_module
Enter fullscreen mode Exit fullscreen mode
  • Navigate inside Project
cd rust_module
Enter fullscreen mode Exit fullscreen mode
  • Project building/compilation
cargo wasi build
Enter fullscreen mode Exit fullscreen mode
  • Project execution
wasmtime target/wasm32-wasi/debug/rust_module.wasm
Enter fullscreen mode Exit fullscreen mode

Code for this tutorial can be found over here
Previous Tutorial

Top comments (0)