search
HomeWeb Front-endJS TutorialCurrency converter in Rust WebAssembly

Currency converter in Rust   WebAssembly

Hi everyone in this post I'm going to show you how to create a simple currency converter written in Rust with WebAssembly, first you need to install Rust using Rust official website below for windows:

(https://www.rust-lang.org/tools/install)

After you install Rust successfully we need to make sure we install WASM or WebAssembly using command below by opening Windows Powershell and run it as administrator:

cargo install wasm-pack

Cargo is a build system and package manager for Rust.

We install Wasm pack or WebAssembly to run Rust on Web view and run HTML code so after successfully installing WebAssembly in Windows Powershell choose the path you want to create files for Rust and then type the command below to create folder and files necessary:

cargo new **folder name of your choice here** --lib
this will create the folder name and files necessary for Rust to run with WebAssembly.

Then we need to modify Cargo.toml file located in your folder that you created with the above command, right click and edit I use notepad (to download notepad use this link (https://notepad-plus-plus.org/) so you will get the option to edit file directly.

in Cargo.toml file write this in it:

[dependencies]
reqwest = { version = "=0.11.7", features = ["json"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"

[dev-dependencies]
wasm-bindgen-test = "0.3"

[lib]
crate-type = ["cdylib"]

Then inside src folder located inside your main folder that first created with Cargo command you will find another file we need to edit it's called lib.rs in this file we will write Rust code:

use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;
use reqwest::Error;
use serde::Deserialize;
use std::collections::HashMap;

#[derive(Deserialize)]
struct ExchangeRates {
    rates: HashMap<string f64>,
}

#[wasm_bindgen]
pub async fn convert_currency(base: String, target: String, amount: f64) -> Result<jsvalue jsvalue> {
    let url = format!("https://api.exchangerate-api.com/v4/latest/{}", base);

    let response = reqwest::get(&url)
        .await
        .map_err(|err| JsValue::from_str(&format!("Failed to fetch rates: {}", err)))?;

    let rates: ExchangeRates = response.json()
        .await
        .map_err(|err| JsValue::from_str(&format!("Invalid response format: {}", err)))?;

    if let Some(&rate) = rates.rates.get(&target) {
        let converted = amount * rate;
        Ok(JsValue::from_f64(converted)) // Return the converted amount
    } else {
        Err(JsValue::from_str(&format!("Currency {} not found", target)))
    }
}

</jsvalue></string>

Then we will get to the part where we need to create folders and files needed for web view.
Open Powershell then navigate to your folder path make sure you're inside the main folder you created with Cargo new command then run this command:

wasm-pack build --target web

This will create folders named pkg and target and other files.

Then at your main folder that you created with cargo new folder name here --lib create HTML file named index.html inside it write this code:



  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Currency Converter</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f0f8ff;
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
    }

    .container {
      background: #ffffff;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
      border-radius: 10px;
      padding: 20px 30px;
      width: 350px;
      text-align: center;
    }

    h1 {
      color: #333;
      margin-bottom: 20px;
    }

    label {
      display: block;
      margin: 10px 0 5px;
      font-weight: bold;
      color: #555;
    }

    input {
      width: 100%;
      padding: 10px;
      margin-bottom: 15px;
      border: 1px solid #ccc;
      border-radius: 5px;
      font-size: 16px;
    }

    button {
      width: 100%;
      padding: 10px;
      background-color: #007bff;
      border: none;
      border-radius: 5px;
      color: white;
      font-size: 16px;
      cursor: pointer;
      transition: background-color 0.3s;
    }

    button:hover {
      background-color: #0056b3;
    }

    .result {
      margin-top: 20px;
      font-size: 18px;
      color: green;
      font-weight: bold;
    }

    .error {
      margin-top: 20px;
      font-size: 16px;
      color: red;
    }
  </style>


  <div>



<p>Make sure that this line import init, { convert_currency } from "../pkg/**name of your folder.js**"; javascript file found in pkg folder make sure it points to the correct .js file normally it's named after your main folder name ends in .js found inside pkg folder.</p>

<p>To run your server on local machine navigate to your main folder that we created with cargo new **folder name here** --lib and run this command to start server on your machine:<br>
python -m http.server<br><br>
to install python refer to <br>
(https://www.python.org/downloads/windows/)</p>

<p>after running the command, open web browser of your choice and type localhost:8000 or 127.0.0.1:8000 and the enter.</p>

<p>You need to enter currency codes for that check this website:<br>
https://taxsummaries.pwc.com/glossary/currency-codes</p>

<p>Hope you enjoy it and apologies for the long post.</p>


          </div>

            
        

The above is the detailed content of Currency converter in Rust WebAssembly. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Custom Google Search API Setup TutorialCustom Google Search API Setup TutorialMar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Example Colors JSON FileExample Colors JSON FileMar 03, 2025 am 12:35 AM

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

8 Stunning jQuery Page Layout Plugins8 Stunning jQuery Page Layout PluginsMar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

What is 'this' in JavaScript?What is 'this' in JavaScript?Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

Improve Your jQuery Knowledge with the Source ViewerImprove Your jQuery Knowledge with the Source ViewerMar 05, 2025 am 12:54 AM

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 Mobile Cheat Sheets for Mobile Development10 Mobile Cheat Sheets for Mobile DevelopmentMar 05, 2025 am 12:43 AM

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft