Skip to content

Rust Example Code

MMDRZA edited this page Oct 18, 2024 · 1 revision
use reqwest;
use serde::Deserialize;
use std::error::Error;

// Define a struct to represent each cryptocurrency data
#[derive(Deserialize, Debug)]
struct Coin {
    symbol: String,
    lastPrice: String,
    highPrice24h: String,
    lowPrice24h: String,
    changeRate: String,
    lastUpdated: String,
}

// Function to fetch cryptocurrency data from the URL
async fn fetch_crypto_data() -> Result<Vec<Coin>, Box<dyn Error>> {
    let url = "https://raw.githubusercontent.com/Crypto-Static/Rate/main/rateStatic.json";
    let response = reqwest::get(url).await?.json::<Vec<Coin>>().await?;
    Ok(response)
}

// Function to display the fetched data
fn display_crypto_data(coins: Vec<Coin>) {
    for coin in coins {
        println!(
            "Symbol: {} | LAST: {} | HIGH: {} | LOW: {} | CHANGE: {} | UPDATED: {}",
            coin.symbol, coin.lastPrice, coin.highPrice24h, coin.lowPrice24h, coin.changeRate, coin.lastUpdated
        );
    }
}

// Main function
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    match fetch_crypto_data().await {
        Ok(coins) => display_crypto_data(coins),
        Err(err) => eprintln!("Error fetching data: {}", err),
    }
    Ok(())
}

Explanation of the Rust Code:

  • reqwest: This is the crate used to perform the HTTP request. It’s asynchronous, which makes it more efficient for handling network operations.
  • serde and serde_json: These are used for deserializing the JSON data into Rust structs. The derive macro helps automatically generate code for converting the JSON into Rust types.
  • async/await: The async function and await keyword handle asynchronous operations, ensuring the program runs efficiently without blocking the main thread.
  • fetch_crypto_data: This function asynchronously sends an HTTP request, waits for the response, and parses it into a Vec<Coin> (a vector of Coin structs).
  • display_crypto_data: This function loops through the parsed data and prints it in a similar format to the Python version.

How to Run:

  1. Add dependencies: In your Cargo.toml file, include the following dependencies:
[dependencies]
reqwest = { version = "0.11", features = ["json"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tokio = { version = "1", features = ["full"] }

Run the project:

cargo run