Coding

10 Rust Programming Code Examples

Problem-solving is what programming is all about. You can't become an expert programmer if you don't practice and build things. This article...

Written by Niel Patel · 3 min read >
Rust Programming Code Examples

Rust has become a fast favourite among programmers thanks to its safety and ease of use. If you’re starting the language, you might want to see some Rust code examples. These can give you a sense of Rust’s capabilities before you invest significantly in learning it.

Whether you’re a professional coder or an enthusiast, you should be familiar with at least one Rust example project.

Rust

There are countless reasons to learn the Rust programming language. Yalantis’ article gives a good run-down of some of the main ways you can benefit from knowing the language.

Some of the world’s biggest tech companies have thrown their weight behind popularizing the language. Unlike some of these corporate efforts, the push toward Rust computer codes has the support of developers. Nearly 20% reported wanting to create projects in Rust.

Get Started With These 10 Rust Programming Codes

Want to take Rust for a test drive? Check out these ten Rust programming codes.

Read a CSV File

Rust can help you read a CSV file without any fuss. Here’s how:

use csv::Error;

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

let csv_data = “

101,Jones,Edward,Samuel.Hiraki@mail.io,Nicaragua,dentist

102,Keller,Yulie,Keller.Yulie@mail.io,Peru,army captain

“;

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(())

}

Find Out How Many CPU Cores You Have

Here’s how to do use Rust to find out how many CPU cores you’re machine is running:

fn main() {

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

}

Finding a program that generates a truly formidable password can be hard. If you’re looking for one, Rust has you covered:

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);

}

With Rust, you’ll get to use a random number generator that works:

use rand::Rng;

fn main() {

let mut range = rand::thread_rng();

let num: i32 = range.gen();

println!(“Random: {}”, n1);

}

Find All the Directory’s txt Files

Forget about manual searches through your directory. Rust can help you find all of your txt files with some simple code:

use glob::glob;

use std::error::Error;

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

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

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

}

Ok(())

}

Decompress a Tarball

Looking for a fast and simple way to decompress a tarball? Rust doesn’t waste your time:

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(())

}

Decode a Base64 String

With Rust, decoding a Base64 string is as easy as using the following code:

use base64::encode;

use std::error::Error;

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

let string = b”Welcome to WebSite”;

let encoded = encode(string);

println!(“Base64: {}”, encoded);

Ok(())

}

Rust has endless real-world applications. Check out how it finds the distance between two points on earth:

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);

}

Convert Your Local Time to a Different Time Zone

Looking for a way to convert your local time into another time zone? Here’s how Rust helps:

use chrono::prelude::*;

let local_time = Local::now();

fn main() {

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

}

Rust can identify a website’s URL scheme:

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

fn main() -> Result ParseError> {

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

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

let scheme = url.scheme();

let host = url.host();

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

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

Ok(())

}

Find All txt Files in a Directory with Rust

use glob::glob;

use std::error::Error;

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

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

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

}

Ok(())

}

Making Use of Rust

Now you’ve seen Rust use cases used in practical settings. If you’re thinking about learning the language, you’ll know where to start and if Rust is for you.

You’ll discover there’s practically no limit to Rust web development. With more programmers learning Rust, a general familiarity with it can only benefit you.

Ethereum Game Development Companies

What Does a Game Developer Do?

Niel Patel in Coding
  ·   3 min read

Leave a Reply