Adapter pattern in Rust - my exploration continues - in Rust, I keep my Trust...


It's truly said that if you teach a person, actually two people learn.

As a guru of my young son, Ridit, I taught him many design patterns and he implemented them in three different languages.

Here's his discussion on Adaptor Design Pattern.

Today I implemented his work of Adapter Pattern using Rust.

In Rust... I keep my Trust.

Rust addresses memory safety and concurrency issues that plague other systems languages like C and C++. This makes it attractive for building reliable, high-performance systems.

Rust is already being used in embedded systems, operating system kernels, and high-performance computing. Rust's memory safety makes it ideal for applications where security is paramount.

In simple words, the future of Rust programming language looks bright.

Here's the source code for the Adapter Design Pattern in Rust.

use std::io;

trait IWeatherFinder {
    fn get_temperature(&self, city_name: &str) -> i32;
}

struct WeatherFinder {}

impl IWeatherFinder for WeatherFinder {
    fn get_temperature(&self, city_name: &str) -> i32 {
        if city_name.trim().eq("Kolkata".trim()) {
            40
        } else {
            println!("Unknown City Name...Could not read temperature");
            -273
        }
    }
}

trait IWeatherFinderClient {
    fn get_temperature(&self, city_pincode: i32) -> i32;
}

struct WeatherAdapter {}

impl WeatherAdapter {
    fn get_city_name(&self, pincode: i32) -> &str {
        if pincode == 700078 {
            "Kolkata".trim()
        } else {
            "UnknownCity"
        }
    }

    fn get_temperature(&self, pincode: i32) -> i32 {
        let city_name = self.get_city_name(pincode);
        let weatherfinder: WeatherFinder = *Box::new(WeatherFinder {});
        weatherfinder.get_temperature(city_name)
    }
}

fn main() {
    println!("Enter pin code");
    let mut pincode = String::new();
    io::stdin().read_line(&mut pincode).expect("Failed to read line");
    let pin_code: i32 = pincode.trim().parse().expect("Input not an integer");
    let weatheradapter = WeatherAdapter {};
    let temperature: i32 = weatheradapter.get_temperature(pin_code);
    println!("The temperature is {} degree Celsius", temperature);
}

Output:

Enter pin code

700078

The temperature is 40 degree celcius

0
Subscribe to my newsletter

Read articles from Somenath Mukhopadhyay directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Somenath Mukhopadhyay
Somenath Mukhopadhyay

To win is no more than this... To rise each time you fall...