The Power of Rust on Linux: A Beginner’s Guide

Jahidul Hasan Hemal
3 min readJul 29, 2024

--

art by Dall-E

Rust is quickly becoming the go-to language for system programming, and it’s not hard to see why. Its unique safety, speed, and concurrency combination make it a perfect fit for Linux development. If you’re new to Rust or Linux, don’t worry — this guide will introduce you to some practical ways you can use Rust to enhance your Linux experience.

Why Rust is Perfect for Linux Development

Before diving into what you can do with Rust on Linux, let’s talk about why Rust is a fantastic choice:

  • Memory Safety: Rust’s ownership model catches memory errors simultaneously, preventing bugs like null pointer dereferencing and buffer overflows.
  • High Performance: Rust’s performance is comparable to C and C++, making it ideal for system-level programming.
  • Concurrency: Rust’s concurrency model helps you write safe, multithreaded code without fear of data races.
  • Robust Tooling: Rust has a rich ecosystem and excellent tools, like Cargo, its package manager and build system.

1. Create Efficient System Utilities

Linux users often need small, efficient tools to manage files, monitor system performance, and automate tasks. Rust’s safety and performance make it an excellent choice for building these utilities.

Example: File Copy Utility

Here’s a simple file copy utility written in Rust. This tool copies the contents of one file to another, demonstrating Rust’s straightforward syntax and powerful standard library.

use std::fs;
use std::env;
use std::io::Result;


fn main() -> Result<()> {
let args: Vec<String> = env::args().collect();
if args.len() != 3 {
eprintln!("Usage: {} <source> <destination>", args[0]);
return Ok(());
}
fs::copy(&args[1], &args[2])?;
Ok(())
}

Usage:

$ cargo run source.txt destination.txt

This command copies source.txt to destination.txt. If successful, there will be no output. If there's an error (e.g., incorrect arguments), it prints:

Usage: target/debug/your_project <source> <destination>

2. Build High-Performance Network Tools

Networking is another area where Rust excels. Whether you’re building a web server, a proxy, or any network-related tool, Rust’s performance and safety guarantees are invaluable.

Example: Basic HTTP Server

Using the hyper crate, you can create a simple HTTP server in Rust. This example listens on port 3000 and responds with "Hello, Rust!" to any request.

use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server};
use std::convert::Infallible;

async fn handle_request(_req: Request<Body>) -> Result<Response<Body>, Infallible> {
Ok(Response::new(Body::from("Hello, Rust!")))
}
#[tokio::main]
async fn main() {
let make_svc = make_service_fn(|_conn| {
async { Ok::<_, Infallible>(service_fn(handle_request)) }
});
let addr = ([127, 0, 0, 1], 3000).into();
let server = Server::bind(&addr).serve(make_svc);
if let Err(e) = server.await {
eprintln!("Server error: {}", e);
}
}

Usage:

$ cargo run
Server running on http://127.0.0.1:3000

Visit http://127.0.0.1:3000 in your browser to see "Hello, Rust!".

3. Develop Automation and Scripting Tools

Rust can replace traditional scripting languages for many tasks, offering the performance and safety of a compiled language.

Example: CPU Usage Monitor

Here’s a script to monitor CPU usage by reading from /proc/stat. It demonstrates Rust’s powerful standard library and file I/O capabilities.

use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;

fn main() {
if let Ok(lines) = read_lines("/proc/stat") {
for line in lines {
if let Ok(cpu_line) = line {
if cpu_line.starts_with("cpu ") {
let parts: Vec<&str> = cpu_line.split_whitespace().collect();
let user: u64 = parts[1].parse().unwrap();
let nice: u64 = parts[2].parse().unwrap();
let system: u64 = parts[3].parse().unwrap();
let idle: u64 = parts[4].parse().unwrap();
println!("CPU Usage: User={} Nice={} System={} Idle={}", user, nice, system, idle);
}
}
}
}
}
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
where
P: AsRef<Path>,
{
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}

Usage:

$ cargo run
CPU Usage: User=600 Nice=10 System=300 Idle=2000

(Note: The numbers are illustrative; actual output will vary based on your system’s state.)

4. Write Cross-Platform Applications

Rust’s ability to target multiple platforms makes it a great choice for developing cross-platform applications. You can write code that runs on Linux, Windows, and macOS with minimal changes.

Example: Cross-Platform CLI Tool

This example shows a simple CLI tool that works across platforms, printing the command-line arguments passed to it.

use std::env;

fn main() {
let args: Vec<String> = env::args().collect();
println!("Arguments: {:?}", args);
}

Usage:

$ cargo run arg1 arg2 arg3
Arguments: ["target/debug/your_project", "arg1", "arg2", "arg3"]

Rust’s unique features make it an excellent choice for Linux development. Whether you’re writing system utilities, network tools, automation scripts, or cross-platform applications, Rust provides the performance, safety, and concurrency you need. Dive into these examples, explore Rust’s rich ecosystem, and join the vibrant community to enhance your development journey. Happy coding!

--

--

Jahidul Hasan Hemal
Jahidul Hasan Hemal

Written by Jahidul Hasan Hemal

A goddamn marvel of modern science. An open-source enthusiast and an optimist who loves to read and watch movies and is trying to learn how to write.

No responses yet