DEV Community

Somenath Mukhopadhyay
Somenath Mukhopadhyay

Posted on

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

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 temparature is {} degree celcius", temperature);

}

Enter fullscreen mode Exit fullscreen mode

Output:

Enter pin code

700078

The temperature is 40 degree celcius

Top comments (0)