<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ben Acq on Medium]]></title>
        <description><![CDATA[Stories by Ben Acq on Medium]]></description>
        <link>https://medium.com/@benacq44?source=rss-6131c09203dd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XDF6KBSpvyKxpc1v93pAWg.jpeg</url>
            <title>Stories by Ben Acq on Medium</title>
            <link>https://medium.com/@benacq44?source=rss-6131c09203dd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 21:16:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@benacq44/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Practical Rust for transitioning engineers]]></title>
            <link>https://medium.com/@benacq44/practical-rust-for-transitioning-engineers-baebaf20468c?source=rss-6131c09203dd------2</link>
            <guid isPermaLink="false">https://medium.com/p/baebaf20468c</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Ben Acq]]></dc:creator>
            <pubDate>Sat, 04 Jan 2025 19:45:00 GMT</pubDate>
            <atom:updated>2025-01-04T19:51:06.655Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This will be the first of a series of articles from the </em><a href="https://www.amazon.com/Programming-Rust-Fast-Systems-Development/dp/1492052590/ref=sr_1_6?dib=eyJ2IjoiMSJ9.Tz8g_DN6JcRbVe0QVT0XH4rZTLxrXPgDsxSSkasm0abyne8nJ9fcMPPpUdxR1CGMl8b4JFLCqNSPQfT-rZP9OSreVuiIGQ_1KqMrJqzqyoBG0ZSzl548ZH5SXmhmwCo72-WW58BOd3n1VvuUnfZWSqHtzKcv_OzUli2z4CCoS35qFLQCvW9l9dV4ItnSeqVOxFMUtQlaz9ke0VbvW1C9AVPvQ11JaT_O4qu6owEHQqF_e956RPoB5GSTIMT8D1hnpwXmZexpv5vQRVezythM4ZMXXhyMtQQ-HdfkGX-6aCIFqo8wbC2whALK1HQacTuXe_Ip4xb8yL2OhLbfD9PpN7ISOLRFpAwdwm4OXVcALuT2a7V1Y6qd3uW-OX4cUBLFNpf_csVLX3GHZdmfHttAZjtknKVvbzIoUaMpUmQR_bxQWjaXnp1gdhkVp0TdfnPl.PFhlT1rW0pCBNQWjvhiROEkh53g_vvkfShnuDncSXg0&amp;dib_tag=se&amp;keywords=rust+programming&amp;qid=1735504420&amp;sr=8-6"><em>Programming Rust book, 2nd Edition</em></a><em>, focusing on the practical sections that can get you up to speed.</em></p><p>Let’s skip the pleasantries and dive straight into building something useful. We will build a system that calculates Greatest Common Divisors (GCD). While calculating GCDs isn’t groundbreaking, the architecture we’ll use demonstrates core Rust concepts in a way that’ll be familiar to experienced engineers.</p><p><strong>Note</strong>: This article assumes you have Rust installed and you are already familiar with the basic syntax, this may not be for you if:</p><ul><li>You’re looking for basic Rust syntax tutorials (variables, loops, functions)</li><li>You’re new to programming and learning your first language and fundamental programming concepts like functions and data structures</li></ul><h3>The Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_PWVtSyDW0KuUUgaJx9yw.png" /><figcaption>A simple architecture for our system</figcaption></figure><h3>Understanding Our Components</h3><p>Looking at the diagram above, we have three distinct components:</p><h4>The Core: GCD Computer</h4><p>This is our library crate, the mathematical engine of our system. In Rust, library crates are non-executable components designed to be shared across different projects. Think of it as:</p><ul><li>Your domain logic in a typical enterprise application</li><li>A reusable module that other Rust programs can depend on</li><li>The single source of truth for GCD calculations in our ecosystem</li></ul><h4>The Frontend</h4><p>We’re building two ways to interact with our GCD computer:</p><ol><li><strong>Web Client</strong></li></ol><ul><li>Provides a simple form to accept 2 numbers</li><li>Sends HTTP requests to the server for GCD calculations</li></ul><p><strong>2. CLI Client</strong></p><ul><li>A command-line interface</li><li>Direct terminal access to GCD functions</li></ul><p>Both clients are binary crates - standalone applications that provide different ways to access the same core functionality.</p><h3>Understanding Crate Types in Rust</h3><p>Rust has two types of crates (think packages in other languages):</p><ul><li><strong>Binary Crates</strong>: These compile into executables you can run. They must have a main function - like our web and CLI clients. Think of them as the final, deployable applications.</li><li><strong>Library Crates</strong>: These are shared codebases meant to be used by other programs , like our GCD computer. They’re the reusable components that other Rust programs can import.</li></ul><p>This distinction is crucial because it affects how we structure our code and how others can use it. Our web and CLI clients are binary crates because they’re end-user applications, while the GCD computer is a library crate because it provides functionality for other programs to use. <a href="https://doc.rust-lang.org/book/ch07-01-packages-and-crates.html"><em>Read more from the docs</em></a></p><h3>What we will be building</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2DqbOqKI6_VFPtG4bQmSQ.gif" /><figcaption>Web client</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mIm5tGbn6N41AYGEV1HBIg.gif" /><figcaption>CLI client</figcaption></figure><h3>Ready to Write Some Rust?</h3><p>Let’s implement our system, starting with setting up our workspace and then our core GCD library. For this tutorial, we’ll be using JetBrains’ RustRover IDE.</p><h3>Setting Up Workspaces</h3><p>For engineers coming from different backgrounds:</p><ul><li><strong>JavaScript developers</strong>: Think of workspaces like npm/yarn workspaces — a way to manage multiple related packages</li><li><strong>Java developers</strong>: Similar to modules in a multi-module Maven/Gradle project</li></ul><p>Let’s create our workspace structure:</p><pre># Create the workspace root<br>cargo new rust-gcd --lib</pre><p>The --lib flag here is significant - it marks our root as a library workspace rather than an executable project. This is a common pattern in Rust for managing multiple related crates.</p><p>Navigate into the workspace and create our three component crates:</p><pre>cd rust-gcd<br>cargo new gcd-core --lib   # Our core library<br>cargo new cli --bin    # Web interface<br>cargo new web --bin    # Command-line interface</pre><p>Note the different flags:</p><ul><li>--lib for our core library (shared functionality)</li><li>--bin for our executables (user-facing applications)</li></ul><h3>Configuring the Workspace</h3><p>Let’s set up our workspace configuration. First, open the root crate in RustRover and navigate to Cargo.toml in the root directory. You should see this configuration:</p><pre>workspace = { members = [ &quot;cli&quot;,&quot;gcd-core&quot;, &quot;web&quot;] }<br><br>[package]<br>name = &quot;articles&quot;<br>version = &quot;0.1.0&quot;<br>edition = &quot;2021&quot;<br><br><br>#[dependencies]</pre><p>If you do not have this configuration for any reason, please copy and replace the configuration you have with this.</p><p>Note that each member crate (gcd-core, cli, and web) will have its own Cargo.toml, but without the workspace section since they&#39;re members, not workspace roots.</p><h3>Implementing GCD core library</h3><p>Go to your gcd-core library and open src/lib.rs, you can then paste the implementation of the gcd function below:</p><pre>pub mod gcd{<br>    pub fn compute_gcd(mut n: u64, mut m: u64) -&gt; u64{<br>        assert!(n != 0 &amp;&amp; m != 0);<br>        while m != 0 {<br>            if m &lt; n {<br>                let t = m;<br>                m = n;<br>                n = t;<br>            }<br>            m = m % n;<br>        }<br>        n<br>    }<br><br>}<br><br><br>#[cfg(test)]<br>mod tests {<br>    use super::gcd::compute_gcd;<br><br>    #[test]<br>    fn test_gcd_computation() {<br>        assert_eq!(compute_gcd(48, 18), 6);<br>        assert_eq!(compute_gcd(54, 24), 6);<br>        assert_eq!(compute_gcd(7, 13), 1); <br>    }<br><br>    #[test]<br>    #[should_panic]<br>    fn test_gcd_zero_input() {<br>        compute_gcd(0, 10);<br>    }<br>}</pre><p>Now we have implemented our GCD core library and tested it, let us briefly talk about the Rust module system and how different it is from other languages.</p><h3>Understanding Rust Modules</h3><p>One key difference when coming to Rust is how it handles modules. Unlike other languages where modules/packages are mapped to files and directories, Rust lets you define modules wherever you want. Your module structure is independent of your file structure. The pub mod gcd declaration creates a module regardless of whether it&#39;s in its own file or nested in another - it&#39;s all about visibility and organization, not file location.</p><p>Next up: We’ll build a command-line interface that uses this core library. Ready to see how workspace dependencies work in Rust?</p><h3>Implementing the CLI Client</h3><p>Now that we have our core GCD library, let’s build a command-line interface for it. Our CLI will be an executable application that users can run directly from their terminal.</p><h4>Adding the Core Library Dependency</h4><p>First, we need to tell Cargo our CLI depends on our GCD library. In cli/Cargo.toml, add:</p><pre>[dependencies]<br>gcd-core = {version = &quot;0.1.0&quot;, path = &quot;../gcd-core&quot; }</pre><p>This tells Cargo:</p><ul><li>We need the gcd-core library</li><li>It’s located in a sibling directory</li></ul><p>Now that we have declared the dependency, go to main.rs in the CLI crate and add code below:</p><pre>use gcd_core::gcd::compute_gcd;<br>struct CliArgs{<br>    function: String,<br>    m: u64,<br>    n: u64<br>}<br><br>fn main() {<br>    let function = std::env::args().nth(1).expect(&quot;no pattern given&quot;);<br>    let m = std::env::args().nth(2).expect(&quot;No m value given&quot;);<br>    let n = std::env::args().nth(3).expect(&quot;No n value given&quot;);<br><br>    let args = CliArgs{<br>        function,<br>        m: m.parse().unwrap(),<br>        n: n.parse().unwrap()<br>    };<br>    let gcd = compute_gcd(args.n, args.m);<br>    println!(&quot;The gcd the numbers {} and {} is {}&quot;, args.m, args.n, gcd);<br><br>}</pre><p>Notice how we import our GCD function: gcd_core::gcd::compute_gcd. In Rust, this path follows the pattern: crate_name::module::item, regardless of the file structure.</p><h3>Running the CLI</h3><p>You can run the CLI in two ways:</p><ol><li>Using Cargo (during development):</li></ol><pre>cargo run -p cli -- gcd 36 20</pre><p>2. Running the compiled binary directly:</p><pre>#relative path<br>./target/debug/cli gcd 36 20<br><br>#absolute path<br>/Users/benacq/Desktop/dev/rust/articles/target/debug/cli gcd 36 20</pre><p>The binary is located in target/debug because we&#39;re building in debug mode. For release builds, you&#39;ll find it in target/release.</p><p>Next up: We’ll implement the web interface to provide HTTP access to our GCD calculator.</p><h3>Implementing the Web Client</h3><p>Our final component is a web server that exposes our GCD calculator via HTTP. This demonstrates how Rust handles web services and external dependencies.</p><h4>Setting Up Dependencies</h4><p>In web/Cargo.toml, we need three dependencies:</p><pre>[dependencies]<br>actix-web = &quot;4&quot;<br>serde = { version = &quot;1.0.217&quot;, features = [&quot;derive&quot;] }<br>gcd-core = {version = &quot;0.1.0&quot;, path = &quot;../gcd-core&quot; }</pre><p>Notice the different dependency styles:</p><ul><li>Remote crates (actix-web, serde): Referenced by version number</li><li>Local crates (gcd-core): Need both version and path</li></ul><p>The features = [&quot;derive&quot;] for serde enables derive macros, which we&#39;ll use to automatically implement serialization for our types.</p><p>Now navigate to the main.rs file and add the code below:</p><pre>use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder};<br>use serde::Deserialize;<br>use gcd_core::gcd::compute_gcd;<br><br><br>#[derive(Deserialize)]<br>struct GcdParameters{<br>    n: u64,<br>    m: u64,<br>}<br><br>#[actix_web::main]<br>async fn main() -&gt; std::io::Result&lt;()&gt; {<br>    HttpServer::new(|| {<br>        App::new()<br>            .service(get_gcd)<br>            .service(post_gcd)<br><br><br>    })<br>        .bind((&quot;127.0.0.1&quot;, 8080))?<br>        .run()<br>        .await<br>}<br><br>#[post(&quot;/gcd&quot;)]<br>async fn post_gcd (form: web::Form&lt;GcdParameters&gt;) -&gt; HttpResponse {<br>    if form.n == 0 || form.m == 0 {<br>        HttpResponse::BadRequest()<br>            .content_type(&quot;text/html&quot;)<br>            .body(&quot;Computing the GCD with zero is boring&quot;);<br>    }<br>    let response = format!(&quot;The GCD of the numbers {} and {} is &lt;b&gt;{}&lt;/b&gt;!&quot;, form.n, form.m, compute_gcd(form.n, form.m));<br>    HttpResponse::Ok().content_type(&quot;text/html&quot;).body(response)<br>}<br><br><br>#[get(&quot;/&quot;)]<br>async fn get_gcd() -&gt; impl Responder {<br>    HttpResponse::Ok()<br>        .content_type(&quot;text/html&quot;)<br>        .body(<br>            r#&quot;<br>            &lt;title&gt;GCD Calculator&lt;/title&gt;<br>                &lt;form action=&quot;/gcd&quot; method=&quot;post&quot;&gt;<br>                &lt;input type=&quot;text&quot; name=&quot;n&quot;/&gt;<br>                &lt;input type=&quot;text&quot; name=&quot;m&quot;/&gt;<br>                &lt;button type=&quot;submit&quot;&gt;Compute GCD&lt;/button&gt;<br>                &lt;/form&gt;<br>            &quot;#<br>        )<br>}</pre><p>After implementing the web server, let’s test our GCD calculator through its HTTP interface.</p><p>From your workspace root, run:</p><pre>cargo run -p web</pre><p>To test it:</p><ul><li>Open your browser and navigate to <a href="http://localhost:8080/">http://localhost:8080</a></li><li>You’ll see a simple form with two input fields</li><li>Enter two numbers (e.g., 48 and 18)</li><li>Click submit to calculate their GCD</li></ul><h3>Summary</h3><p>In this article, we explored practical Rust development by building a Greatest Common Divisor (GCD) calculator system. The project demonstrated several fundamental Rust concepts and best practices through a multi-crate architecture:</p><h3>Key Concepts Covered</h3><h4>Workspace and Project Structure</h4><ul><li>Organization of Rust projects using workspaces to manage multiple related crates</li><li>Distinction between binary crates (executables) and library crates (shared code)</li><li>Configuration of workspace dependencies using Cargo.toml</li></ul><h4>Rust Module System</h4><ul><li>Creation and organization of modules using pub mod</li><li>Independence of module structure from file system structure</li></ul><h4>Testing in Rust</h4><ul><li>Implementation of unit tests using the #[test] attribute</li><li>Test organization within module blocks</li><li>Testing for expected panics using #[should_panic]</li></ul><h4>Web Development with Rust</h4><ul><li>Usage of the Actix-web framework for HTTP services</li><li>Request handling with both GET and POST endpoints</li><li>Form data processing and response generation</li><li>Integration of third-party crates (actix-web, serde)</li></ul><h4>CLI Development</h4><ul><li>Command-line argument parsing</li><li>Error handling for missing arguments</li></ul><p>This project serves as a practical introduction to Rust development, demonstrating how to structure a real-world application while incorporating essential Rust concepts and patterns.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=baebaf20468c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>