Rust Lang

16 Rust Programming Code Examples

Programming is all about problem-solving. There is no way you can become a proficient programmer without practicing and building things. In this article we will create projects to get you started in the Rust programming language.

Get Largest String

The first program attempts to determine the largest string from two string pairs. The example source code is as shown below:

fn largest<'a>(str1:&'a str, str2:&'a str) -> &'a str {

if str1.len() > str2.len(){

str1

} else {

str2

}

}

fn main() {

let str1 = "Hello";

let str2 = "linuxhint";

let result = largest(str1, str2);

println!("Largest: {}", result);

}

Compress Directory into Tarball

The second program compresses the provided directory into a tarball. The source code example is as shown:

NOTE: This code requires flate2 compression/decompression library.

use std::fs::File;

use flate2::Compression;

use flate2::write::GZEncoder;

fn main() -> Result<(), std::io::Error>{

let gz = File::create("archive.tar.gz");

let encoder = GZEncoder::new(gz, Compression::default());

let mut tar = tar::Builder::new(enc);

// add all files in the current directory to current_backup

tar.append_dir_all(".", "current_backup")?;

Ok(());

}

Decompress Tarball

Next is a program to decompress a tarball. The source code is as shown below:

use std::fs::File;

use std::path::PathBuf;

use flate2::read::GzEncoder;

use tar::Archive;

use std::error::Error;

fn main() -> Result<(), Box<dyn Error>>{

let file = File::open("path/to/archive.tar.gz")?;

let mut archive = Archive::new(GzEncoder::new(file));

println!("Extracted: ");

archive

.entries()?

.filter_map(|e| e.ok())

.map(|mut entry| -> Result<PathBuf, Box<dyn Error>> {

let path = entry.path()?.to_owned();

Ok(path.to_path_buf())

})

.filter_map(|e| e.ok())

.for_each(|x| println!("> {}", x.display()));

Ok(())

}

Find All txt Files in a Directory

The next program we can build is one that finds all txt files within a directory: The code is as provided below:

use glob::glob;

use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {

for item in glob("**/*.txt")?{

println!("{}", item?.display());

}

Ok(())

}

Generate Random Numbers

A simple program to generate random numbers.

use rand::Rng;

fn main() {

let mut range = rand::thread_rng();

let num: i32 = range.gen();

println!("Random: {}", n1);

}

Password Generator

We can create a password generator by generating random alphanumeric characters. Code is as shown:

use rand::Rng;

const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\

abcdefghijklmnopqrstuvwxyz\

0123456789)(*&^%$#@!"
;

const LEN: i32 = 25;

fn main() {

let mut rng = rand::thread_rng();

let password: String = (0..LEN)

.map(|_| {

let idx = rng.gen_range(0..CHARSET.len());

CHARSET[idx] as char

})

.collect();

println!("Password: {}", password);

}

Read CSV

The next program is to read a CSV file. The code is a shown:

use csv::Error;

fn main() -> Result<(), Error> {

let csv_data = "

101,Edith,Masao,[email protected],Colombia,doctor

102,Kellen,Yusuk,[email protected],Nicaragua,police officer

"
;

let mut reader = csv::Reader::from_reader(csv_data.as_bytes());

for row in reader.records() {

let row = row?;

println!(

"id {} | firstname: {} | lastname: {} | email: {} | country: {} | profession: {} |",

&row[0],

&row[1],

&row[2],

&row[3],

&row[4],

&row[5],

);

}

Ok(())

}

Number of CPU Cores

Get the number of logical CPU cores in the program:

fn main() {

println!("CPU Cores: {}", num_cpus::get());

}

Sort Vector (i32)

You can sort a vector as:

fn main() {

let mut vec = vec![1,23,42,23,45,223,211,122,233,799,123];

vec.sort();

println!("Sorted: {:?}", vec)

}

Sort Vector (f64)

You can also sort a vector of floating-point values as:

fn main() {

let mut vec = vec![23.12, 3.44, 5.55, 34.90, 2.0];

vec.sort_by(|x, y| x.partial_cmp(y).unwrap());

println!("Sorted: {:?}", vec);

}

Log Message to Console

You can use the log create to create log messages. A simple example is as shown below:

fn log(command: &str) {

log::debug!("Running command: {}", command);

}

fn main() {

env_logger::init();

log("ps aux | grep bash");

// run with command:

// RUST_LOG=debug cargo run

}

Encode Base64

The code below shows a program to encode a string to base64.

use base64::encode;

use std::error::Error;

fn main() -> Result<(), Box<dyn Error>>{

let string = b"Welcome to Linuxhint";

let encoded = encode(string);

println!("Base64: {}", encoded);

Ok(())

}

Decode Base64

We can decode Base64 string as:

use base64::decode;

use std::str;

use std::error::Error;

fn main() -> Result<(), Box<dyn Error>>{

let b64 = "V2VsY29tZSB0byBMaW51eGhpbnQ=";

let decoded = &decode(b64).unwrap()[..];

println!("String: {:?}", str::from_utf8(decoded));

Ok(())

}

Convert Local Time to Another Time Zone

The program below converts local time into specified time zone. Code is as shown below:

use chrono::prelude::*;

fn main() {

let local_time = Local::now();

let utc = DateTime::<Utc>::from_utc(local_time.naive_utc(), Utc);

let est = FixedOffset::east(5 * 3600);

println!("Local Time: {} EAT", local_time);

println!("UTC Time now: {}", utc);

println!("EST Time Now: {}", utc.with_timezone(&est));

// example output

// Local Time: 2022-02-27 14:50:31.014429200 +03:00 EAT

// UTC Time now: 2022-02-27 11:50:31.014429200 UTC

// EST Time Now: 2022-02-27 16:50:31.014429200 +05:00

}

Distance Between Two Points on Earth

We can calculate the distance between two points on earth based on longitude and latitude as shown in the example below:

const EARTH_RADIS: f64 = 6378.1370;

fn main() {

let nairobi_lat_deg = -1.286389_f64;

let nairobi_long_deg = 36.817223_f64;

let el_paso_lat_deg = 31.772543_f64;

let el_paso_long_deg = -106.460953_f64;

let nairobi_lat = nairobi_lat_deg.to_radians();

let el_paso_lat = el_paso_lat_deg.to_radians();

let delta_lat = (nairobi_lat_deg - el_paso_lat_deg).to_radians();

let delta_long = (nairobi_long_deg - el_paso_long_deg).to_radians();

let angle_inner = (delta_lat / 2.0).sin().powi(2) +

nairobi_lat.cos() * el_paso_lat.cos() * (delta_long / 2.0).sin().powi(2);

let central_angle = 2.0 * angle_inner.sqrt().asin();

let distance = EARTH_RADIS * central_angle;

println!("Distance between Nairobi and El Paso is: {:.2} KM", distance);

}

Extract URL Scheme

We can extract the host and scheme from a provided URL string as:

use url::{Url, Host, ParseError};

fn main() -> Result<(), ParseError> {

let string = "https://linuxhint.com";

let url = Url::parse(string)?;

let scheme = url.scheme();

let host = url.host();

println!("Scheme: {}", scheme);

println!("Host: {:?}", host);

Ok(())

}

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list