<?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 Raunak on Medium]]></title>
        <description><![CDATA[Stories by Raunak on Medium]]></description>
        <link>https://medium.com/@raunakthakkar4?source=rss-9f618953b580------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-mkYx3ocum0Xx0FD.jpg</url>
            <title>Stories by Raunak on Medium</title>
            <link>https://medium.com/@raunakthakkar4?source=rss-9f618953b580------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:46:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@raunakthakkar4/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[Rust Futures, End to End]]></title>
            <link>https://medium.com/rustaceans/rust-futures-end-to-end-49406b374c76?source=rss-9f618953b580------2</link>
            <guid isPermaLink="false">https://medium.com/p/49406b374c76</guid>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[async-rust]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Raunak]]></dc:creator>
            <pubDate>Wed, 05 Aug 2026 06:49:58 GMT</pubDate>
            <atom:updated>2026-08-05T06:49:58.817Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*GT0w5vSRxke1-NLEeyP7bQ.png" /></figure><p><em>What a future actually is, how a runtime consumes it, how you write one, how the compiler turns your </em><em>async fn into a machine that remembers what it was doing, and where you&#39;d reach for all this.</em></p><h3>1. What a future is</h3><p>A <strong>future</strong> is a value that represents a computation that isn’t finished yet. It is the thing an async fn hands back to you. Not the result — the <em>promise of a result</em>, packaged as an object you can hold, pass around, and eventually drive to completion.</p><p>The entire concept fits in one trait:</p><pre>trait Future {<br>    type Output;<br>    fn poll(&amp;mut self, cx: &amp;mut Context) -&gt; Poll&lt;Self::Output&gt;;<br>}</pre><pre>enum Poll&lt;T&gt; {<br>    Ready(T),   // done — here&#39;s the value<br>    Pending,    // not done — check back later<br>}</pre><p>That’s it. A future is anything with a poll method that, when called, either says &quot;here&#39;s your value&quot; (Ready) or &quot;not yet&quot; (Pending). Everything else — async, .await, Tokio, Actix — is built on this one idea.</p><p>Two properties define how futures behave, and both differ from JavaScript Promises:</p><p><strong>Futures are lazy.</strong> Calling an async fn runs <em>none</em> of its body. It just constructs the future value and returns it, inert. Contrast JS, where calling an async function starts the work immediately. In Rust, a future that is never driven simply never runs — the code inside it does nothing at all.</p><pre>async fn do_work() { println!(&quot;working!&quot;); }</pre><pre>fn main() {<br>    let fut = do_work();   // prints NOTHING — the body hasn&#39;t run<br>    // fut is just sitting here, a paused computation<br>}</pre><p><strong>Futures are passive.</strong> A future does not run itself. Something external has to repeatedly call poll to push it forward. That &quot;something&quot; is the runtime.</p><h3>2. How a runtime consumes a future</h3><p>A future is inert; a <strong>runtime</strong> is the engine that brings it to life. Tokio is the common one (Actix Web runs on it). The runtime’s job is to <em>drive</em> futures — “driving” meaning: call poll over and over until the future returns Ready.</p><p>Naively, driving one future looks like this:</p><pre>loop {<br>    match future.poll(cx) {<br>        Poll::Ready(value) =&gt; break value,   // done<br>        Poll::Pending      =&gt; park_until_woken(),  // wait, then poll again<br>    }<br>}</pre><p>But a real runtime does something smarter than busy-looping. When a future returns Pending, it first registers a <strong>waker</strong> — a callback meaning &quot;ping me when there&#39;s a reason to poll me again.&quot; The runtime then <em>parks</em> that future and goes off to drive other futures. It does not touch the parked one again until its waker fires.</p><p>The full cycle:</p><ol><li>Runtime calls poll on a future.</li><li>The future runs as far as it can, then hits an .await on something not ready (a socket with no data yet, a timer that hasn&#39;t elapsed).</li><li>It stores a waker and returns Pending.</li><li>The runtime parks it and drives other tasks meanwhile — this is the concurrency.</li><li>The outside world (the OS) reports the I/O is ready and fires the waker.</li><li>The waker tells the runtime: “re-poll this one.”</li><li>Runtime polls again; the future resumes and eventually returns Ready.</li></ol><p>Drawn out, the loop looks like this:</p><pre>poll()<br>             ┌──────────────────►┐<br>             │                   │<br>          ┌──┴──────┐   Pending  │    ┌──────────┐<br>          │ RUNTIME │◄───────────┴────┤  FUTURE  │<br>          │ drives  │  &quot;not yet,      │ paused   │<br>          │ futures │   here&#39;s my     └────┬─────┘<br>          └──┬──────┘   waker&quot;             │ waits on<br>             │  meanwhile: drive           │<br>             │  other parked futures       ▼<br>             │                        ┌──────────┐<br>             │       wake()           │  OS / IO │<br>             └◄───────────────────────┤ socket,  │<br>                  &quot;re-poll this one&quot;  │ timer    │<br>                  (IO is ready now)   └──────────┘</pre><pre>   ...runtime polls again ──► Ready(value) ──► done</pre><p>The future never drives itself. The runtime pushes it forward on each poll; the OS decides <em>when</em> there&#39;s a reason to, by ringing the waker. In between, that one runtime thread is off driving other parked futures — which is exactly where the concurrency comes from.</p><p>Under the hood the runtime does two jobs: it keeps polling the futures that are ready to make progress, and it watches the OS to find out when a waiting one’s I/O has become ready so it can fire that future’s waker. One part pushes futures forward; the other part knows when there’s a reason to.</p><p>This design is why one thread can hold thousands of futures at once. A parked future costs almost nothing — just its small state struct sitting in memory — whereas giving each connection its own OS thread is far more expensive. Thread-per-connection servers fall over at a few thousand connections; async servers handle hundreds of thousands. That is the whole performance argument for async, and the reason Actix benchmarks near the top of web-framework charts.</p><p>The framing worth remembering: <strong>JavaScript <em>pushes</em> a promise forward eagerly; Rust <em>pulls</em> a future forward by polling — but only when a waker says there’s a reason to.</strong> Push versus pull.</p><pre>JavaScript — PUSH (eager)          Rust — PULL (lazy)<br>   ─────────────────────────          ──────────────────────────<br>   create promise                     create future<br>        │  starts running NOW              │  runs NOTHING<br>        ▼                                  ▼<br>   ┌───────────┐                      ┌──────────┐   ┌──────────┐<br>   │  work     │                      │runtime   │──►│  future  │<br>   │  runs     │─── result ──►        │ poll()   │◄──│  inert   │<br>   │           │                      │          │   │   until  │<br>   │  itself   │    pushed            └──────────┘   │  polled  │<br>   └───────────┘    to you                           └──────────┘<br>   no one has to ask for it           polls only when a waker says so</pre><h3>3. How a developer writes futures</h3><p>You almost never implement poll by hand. You write async / .await and the compiler builds the future for you.</p><p><strong>Writing one.</strong> Mark a function async and it returns a future:</p><pre>async fn fetch_user(id: u32) -&gt; String {<br>    format!(&quot;user #{id}&quot;)<br>}</pre><p>Calling fetch_user(7) doesn&#39;t give you a String. It gives you a Future&lt;Output = String&gt; — a paused computation that will <em>produce</em> a String once driven.</p><p><strong>Consuming one.</strong> Inside another async context, .await drives a future to completion and unwraps its value:</p><pre>async fn handler() -&gt; String {<br>    let user = fetch_user(7).await;   // drive it; when Ready, bind the value<br>    format!(&quot;loaded {user}&quot;)<br>}</pre><p>.await means: &quot;poll this inner future; if it&#39;s Pending, pause <em>me</em> too and hand control back to the runtime; when it&#39;s Ready, resume here with the value.&quot; That&#39;s the only place suspension happens — at an .await.</p><p><strong>Starting the whole thing.</strong> At the top you need a runtime to do the actual driving. That’s what #[tokio::main] or #[actix_web::main] sets up:</p><pre>#[tokio::main]<br>async fn main() {<br>    let msg = handler().await;<br>    println!(&quot;{msg}&quot;);<br>}</pre><p>The macro wraps main so it can be async, spins up the runtime, and hands your top-level future to it. Without a runtime, nothing drives anything, and your futures never run.</p><p><strong>Running several concurrently.</strong> .await alone runs futures one after another. To overlap them, use combinators:</p><pre>// Both run concurrently; finishes when the slower one does.<br>let (a, b) = tokio::join!(fetch_user(1), fetch_user(2));</pre><pre>// Hand a task to the executor to run independently, like a green thread.<br>let handle = tokio::spawn(async { fetch_user(3).await });<br>let c = handle.await.unwrap();</pre><p><strong>The one trap.</strong> Never do <em>blocking</em> work inside an async context. A std::thread::sleep, a heavy CPU loop, or a synchronous file read blocks the entire executor thread — it can&#39;t poll any other future while stuck. Use the async equivalents (tokio::time::sleep) for waits, and push CPU-bound work off the async threads with tokio::task::spawn_blocking (or web::block in Actix). This is the most common real-world async bug.</p><h3>4. How Rust internally writes an async fn to remember what it&#39;s doing</h3><p>Here’s the part that feels like magic and isn’t. A normal function keeps its local variables on the stack; when it returns, the stack frame — and every local — is destroyed. So how can a future stop halfway, return control, and later resume with its variables intact?</p><p><strong>The compiler rewrites every </strong><strong>async fn into an enum-based state machine.</strong> Each .await becomes a <em>state</em>. &quot;Where it paused&quot; is just which enum variant the future currently holds. The still-needed local variables are stored <em>inside</em> the variant, so they survive across poll calls instead of dying on a stack frame.</p><p>Take this:</p><pre>async fn handler() -&gt; String {<br>    let a = fetch_user().await;      // pause point 1<br>    let b = fetch_orders(a).await;   // pause point 2<br>    format!(&quot;{a} {b}&quot;)<br>}</pre><p>The compiler produces, conceptually, an enum like:</p><pre>enum Handler {<br>    Start,<br>    WaitingUser   { fut: FetchUser },<br>    WaitingOrders { a: User, fut: FetchOrders },  // note: `a` is stored here<br>    Done,<br>}</pre><p>WaitingOrders carries a because step 2 still needs it after the wait. That storage <em>is</em> the mechanism for surviving a pause.</p><p>Each .await is one variant, and the locals that must outlive the pause ride <em>inside</em> it:</p><pre>┌─────────┐   ┌────────────────────┐   ┌──────────────────────────┐    ┌──────┐<br>│  Start  │──►│    WaitingUser     │──►│      WaitingOrders       │──► │ Done │<br>│         │   │  { fut: FetchUser }│   │ { a: User,               │    │      │<br>│ holds:  │   │  holds:            │   │   fut: FetchOrders }     │    │ ✓    │<br>│ nothing │   │   fut              │   | holds: a  ◄── kept alive │    │      │<br>└─────────┘   └────────────────────┘   |        across the pause  │    └──────┘<br>                     │                 └──────────────────────────┘<br>       Pending? ─────┘  freeze in THIS variant, return.<br>                        self keeps holding it; next poll()<br>                        reads the tag and jumps straight back in.</pre><p>The current variant <em>is</em> the pause point. Resuming isn’t re-running anything — it’s reading a tag and jumping to a branch, with the in-flight locals already sitting in the variant where you left them.</p><p>And poll becomes a match that jumps to the current state:</p><pre>fn poll(&amp;mut self, cx: &amp;mut Context) -&gt; Poll&lt;String&gt; {<br>    loop {<br>        match self {<br>            Start =&gt; {<br>                *self = WaitingUser { fut: fetch_user() };<br>            }<br>            WaitingUser { fut } =&gt; match fut.poll(cx) {<br>                Poll::Pending     =&gt; return Poll::Pending,   // freeze in THIS state<br>                Poll::Ready(user) =&gt; {<br>                    *self = WaitingOrders { a: user, fut: fetch_orders(user) };<br>                }<br>            },<br>            WaitingOrders { a, fut } =&gt; match fut.poll(cx) {<br>                Poll::Pending       =&gt; return Poll::Pending, // freeze in THIS state<br>                Poll::Ready(orders) =&gt; {<br>                    let out = format!(&quot;{a} {orders}&quot;);<br>                    *self = Done;<br>                    return Poll::Ready(out);<br>                }<br>            },<br>            Done =&gt; unreachable!(),<br>        }<br>    }<br>}</pre><p>Now “resume from where it paused” is completely demystified. When WaitingUser returns Pending, self keeps holding that variant. The runtime parks the future — but the <em>struct</em> stays alive. Later the runtime calls poll again on the same struct; the match reads self, sees WaitingUser, and jumps straight into that arm, skipping Start. It doesn&#39;t re-run anything before the pause. It lands on the branch for the pause point. Resuming is reading a tag and jumping to a branch.</p><p>The reason this works where a normal function can’t: the future’s state lives in a struct that outlives any single poll call, not on a stack frame that dies when poll returns.</p><p>One loose end this creates: because those locals live in a struct the runtime moves around in memory, a future holding a reference <em>into itself</em> would break if the struct were relocated mid-flight. <strong>Pin</strong> exists to promise &quot;don&#39;t move me once I&#39;ve started,&quot; protecting the addresses of variables parked inside a suspended state machine. You rarely write it by hand, but that&#39;s why it exists.</p><h3>5. What futures are used for</h3><p>Anywhere a program would otherwise sit idle waiting, futures let it do other work instead. The big categories:</p><ul><li><strong>Network servers.</strong> The headline use. Actix Web, Axum, and friends give each connection a future; one thread juggles thousands, because most are parked waiting on sockets. This is where async earns its keep.</li><li><strong>Clients and outbound I/O.</strong> HTTP calls (reqwest), database queries (sqlx), Redis, message queues — anything where you fire a request and wait on a response. .await the call; the thread serves others meanwhile.</li><li><strong>Concurrency without threads.</strong> join! to run independent requests at once, select! to race several and take whichever finishes first (e.g. a request versus a timeout), spawn to launch background tasks.</li><li><strong>Timers and scheduling.</strong> tokio::time::sleep, intervals, timeouts — all futures, so waiting never blocks a thread.</li><li><strong>Streams.</strong> A Stream is the async cousin of an iterator: a future-like source that yields many values over time (WebSocket messages, rows from a query, lines from a socket).</li></ul><p>The unifying theme: futures are for <strong>I/O-bound and wait-bound</strong> work, where the bottleneck is waiting on something external. They are <em>not</em> a speedup for CPU-bound work — a tight numeric loop should go on a thread pool (spawn_blocking / Rayon), not into an async task, or it&#39;ll block the executor.</p><h3>6. Examples</h3><h3>Easy: one future, awaited</h3><p>A single async function, driven to completion by the runtime.</p><pre>async fn greet(name: &amp;str) -&gt; String {<br>    format!(&quot;hello, {name}&quot;)<br>}</pre><pre>#[tokio::main]<br>async fn main() {<br>    // greet(...) builds a future; .await drives it and yields the String<br>    let msg = greet(&quot;Raunak&quot;).await;<br>    println!(&quot;{msg}&quot;);   // hello, Raunak<br>}</pre><p>What to notice: greet(&quot;Raunak&quot;) on its own runs nothing. .await is what drives it. #[tokio::main] is the runtime that makes any of it happen.</p><h3>Hard: a hand-written future with a real waker</h3><p>To see what the compiler and runtime normally hide, here’s a future implemented by hand — no async sugar. It completes only after a background thread wakes it, which forces you to touch poll, Pending, and the waker directly.</p><pre>use std::future::Future;<br>use std::pin::Pin;<br>use std::sync::{Arc, Mutex};<br>use std::task::{Context, Poll, Waker};<br>use std::thread;<br>use std::time::Duration;</pre><pre>/// Shared state between the future and the thread that completes it.<br>struct Shared {<br>    done: bool,<br>    waker: Option&lt;Waker&gt;,<br>}</pre><pre>/// A future that resolves after `delay`, driven by a background thread.<br>struct Delay {<br>    shared: Arc&lt;Mutex&lt;Shared&gt;&gt;,<br>}</pre><pre>impl Delay {<br>    fn new(delay: Duration) -&gt; Self {<br>        let shared = Arc::new(Mutex::new(Shared { done: false, waker: None }));</pre><pre>        // Background thread: after the delay, mark done and wake the runtime.<br>        let bg = Arc::clone(&amp;shared);<br>        thread::spawn(move || {<br>            thread::sleep(delay);<br>            let mut s = bg.lock().unwrap();<br>            s.done = true;<br>            if let Some(waker) = s.waker.take() {<br>                waker.wake();   // &lt;-- tells the runtime: &quot;poll me again&quot;<br>            }<br>        });</pre><pre>        Delay { shared }<br>    }<br>}</pre><pre>impl Future for Delay {<br>    type Output = &amp;&#39;static str;</pre><pre>    fn poll(self: Pin&lt;&amp;mut Self&gt;, cx: &amp;mut Context&lt;&#39;_&gt;) -&gt; Poll&lt;Self::Output&gt; {<br>        let mut s = self.shared.lock().unwrap();<br>        if s.done {<br>            Poll::Ready(&quot;finished&quot;)           // done — hand back the value<br>        } else {<br>            s.waker = Some(cx.waker().clone()); // stash the waker...<br>            Poll::Pending                       // ...and report &quot;not yet&quot;<br>        }<br>    }<br>}</pre><pre>#[tokio::main]<br>async fn main() {<br>    // Even a hand-rolled future is awaited exactly like any other.<br>    let result = Delay::new(Duration::from_millis(500)).await;<br>    println!(&quot;{result}&quot;);   // finished  (after ~500ms)<br>}</pre><p>Trace the flow and every concept from this article shows up in one place:</p><ul><li>.await on the Delay makes the runtime call poll.</li><li>First poll: not done → the future <strong>stashes the waker</strong> and returns Pending. The runtime parks it and does other work.</li><li>The background thread finishes sleeping, sets done = true, and calls waker.wake() — <strong>the OS-side event firing the waker</strong>.</li><li>The runtime <strong>re-polls</strong>; now done is true, so poll returns Ready(&quot;finished&quot;), and .await produces the value.</li></ul><p>This is precisely what tokio::time::sleep(...).await does internally, and what the compiler builds for you at every .await in ordinary async code. The async keyword just writes this — the state, the stored waker, the Pending/Ready branches — automatically.</p><h3>The one-paragraph summary</h3><p>A future is a lazy, passive value with a single poll method that returns Ready(value) or Pending. A runtime drives it — polling it, parking it when Pending, and re-polling when a waker (rung by the OS) says there&#39;s a reason to — so one thread can juggle thousands of waiting tasks. You write futures with async/.await and never touch poll; the compiler rewrites each async fn into an enum state machine whose current variant is the pause point and whose in-flight locals live inside that variant, which is exactly how a future resumes from where it paused with its variables intact. Reach for all of this whenever the work is waiting on I/O — servers, clients, timers, streams — and keep CPU-bound work off the async threads.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49406b374c76" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rustaceans/rust-futures-end-to-end-49406b374c76">Rust Futures, End to End</a> was originally published in <a href="https://medium.com/rustaceans">Rustaceans</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load-balancing adventures and seeing them in action.]]></title>
            <link>https://medium.com/@raunakthakkar4/load-balancing-adventures-and-seeing-them-in-action-77bc1fbfee31?source=rss-9f618953b580------2</link>
            <guid isPermaLink="false">https://medium.com/p/77bc1fbfee31</guid>
            <category><![CDATA[load-balancing-algorithm]]></category>
            <category><![CDATA[load-balancer]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Raunak]]></dc:creator>
            <pubDate>Sun, 05 May 2024 10:49:27 GMT</pubDate>
            <atom:updated>2024-05-05T10:49:27.390Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*xOdw_euGi-qW_HarG5dqhQ.png" /></figure><p>On a quest to understand load-balancing, i learned many things, in this article we’ll cover those.</p><ol><li>what the heck is Load Balancing.</li><li>how to balance load.</li><li>different ways to balance it.</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F25pONnxiVNYbLJWO41%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExcmZvNXVpbDM4aThnZjgwNTd4a2hkZzN0MXFsZmNhMm5qZmVnNGo1MSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F25pONnxiVNYbLJWO41%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExY3Vna2ZqY3NvaGI4ZG1uMmFwMmswMjc0ZDJjczdzNzh6ZHFqemo4aiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F25pONnxiVNYbLJWO41%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="265" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d1dae5a48bcda759143200e1fa1efc7/href">https://medium.com/media/1d1dae5a48bcda759143200e1fa1efc7/href</a></iframe><p>Load-Balancing (computing) is a process that distributes a set of tasks (requests) to available resources (servers) who can process these tasks. This involves setting up a load-balancer 😎 who is in-charge of forwarding / distributing tasks to the resources. then load-balancer does not directly starts forwarding, there are multiple ways a load-balancer can achieve this.</p><p>But the question arise which is the best way to forward, so that we achieve maximum efficiency from the resources.</p><p>coming to 2nd Point, how to balance load? the answer to this is “Algorithms”, Load-balancing algorithms are logic that contains certain steps that navigate network traffic to different servers, that is implemented with the help of different tools which are already in the market like NGINX / CLOUD-FLARE-BALANCING / HA-PROXY and others.</p><p>3rd Point stating different ways to achieve load-balancing there are few load-balancing algorithms which help us to achieve this, listing some.</p><ul><li><em>Least connection:</em> Checks which servers have the fewest connections open at the time and sends traffic to those servers.</li><li><em>Weighted least connection:</em> Gives administrators the ability to assign different weights to each server, assuming that some servers can handle more connections than others.</li><li><em>Weighted response time:</em> Averages the response time of each server, and combines that with the number of connections each server has open to determine where to send traffic. By sending traffic to the servers with the quickest response time, the algorithm ensures faster service for users.</li><li><em>Round robin:</em> <a href="https://www.cloudflare.com/learning/dns/glossary/round-robin-dns/">Round robin load balancing</a> distributes traffic to a list of servers in rotation using the <a href="https://www.cloudflare.com/learning/dns/what-is-dns/">Domain Name System (DNS)</a>. An authoritative nameserver will have a list of different <a href="https://www.cloudflare.com/learning/dns/dns-records/dns-a-record/">A records</a> for a domain and provides a different one in response to each DNS query.</li><li><em>Weighted round robin:</em> Allows an administrator to assign different weights to each server. Servers deemed able to handle more traffic will receive slightly more. Weighting can be configured within <a href="https://www.cloudflare.com/learning/dns/dns-records/">DNS records</a>.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FCzIGolPSO1HlAEOa0I%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExMHlpaXNldWh3cDR1bHUzNW9kbmR4eWcyb2didHFhcTluaHF4MXQwMyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FCzIGolPSO1HlAEOa0I%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExcjZ4NDE3dXh3bXY0dXd6cGwzdmw1aTJwZWVoMGVuYmhyZHJsenNxMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FCzIGolPSO1HlAEOa0I%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="365" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5ff17d5c815c77941d4290de5560480/href">https://medium.com/media/d5ff17d5c815c77941d4290de5560480/href</a></iframe><p>Now as we have know what is load balancing let’s try to implement it. <strong>We’ll implement load-balancing by setting up NGINX</strong></p><p>To use Nginx, you need to install it, as i am using a MAC, i installed it using brew <strong>brew install nginx </strong>, after successfully installing nginx, i can check it with nginx -v which gives the output of <strong>“nginx version: nginx/1.25.5”</strong></p><p>After this we need to configure NGINX as a load balance, to configure it we need to find nginx.conf file and update with appropriate values</p><p>To find the nginx.conf file you can use nginx -t , this cmd will tell you where’s the configuration file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TCYndpYYpxjAX4GDMOw9w.png" /><figcaption>path to nginx.conf</figcaption></figure><p>lastly we need to update it, to update it we need to understand this file, nginx has its own grammar, let’s take a look. It consists of “context” &amp; “directives”, directives are key-value pair which help us understand the context. And context is a block/ scope with a title on its left that defines the purpose of the scope.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*GnM-i4k2qHQXz-WUtET7UA.png" /></figure><p>In the above given picture, “events” is a scope, the block is denoted by { } brackets and the high-lighted part is a directive.</p><p>To setup NGINX as a load-balancer, we require a special scope that is upstream followed by any name, for eg: “upstream myservers”. And this scope will be nested inside a scope named http so the file will look something like this.</p><pre>http {<br><br>    upstream mybackendserver {}<br>}</pre><p>Next step is to mention all the IP’s withing the upstream scope</p><pre> upstream mybackendserver {<br>    server 127.0.0.1:1111;<br>    server 127.0.0.1:2222;<br>    server 127.0.0.1:3333;<br>    server 127.0.0.1:5555;<br>    }</pre><p>and now as we have all the IP’s with us, we need to tell NGINX to route every incoming requests to the all the servers mentioned above. For this we’ll use server scope with couple of other directives.</p><pre>   server{<br>        listen 8080;<br>        rewrite ^/number/(\w+)/count/$1;<br>        location / {<br>            proxy_pass http://mybackendserver<br>        }<br>    } </pre><p>So the above snippet says, that nginx will listen to Port 8080 and as any request will contain “/” nginx will pass the requests to upstream scope, but here’s the catch, as there’s a list of server, NGINX is smart, it will pass the request 1 by 1 to to each server, that is the default way of forwarding the requests in NGINX and it is known as <strong>ROUND-ROBIN </strong>technique.</p><p>lastly the file looks something like this</p><pre>http {<br><br>    include mime.types;<br><br>    upstream mybackendserver {<br>    server 127.0.0.1:1111;<br>    server 127.0.0.1:2222;<br>    server 127.0.0.1:3333;<br>    server 127.0.0.1:5555;<br>    }<br><br>    server{<br>        listen 8080;<br>        rewrite ^/number/(\w+)/count/$1;<br>        location / {<br>            proxy_pass http://mybackendserver<br>        }<br>    }   <br>}</pre><p>Conclusion :- Load balancing is distributing tasks to appropriate resources so that task execution happens and a system can avoid down-time, load-balancing algorithms and tools help us to achieve this.</p><p>That’s it for now, Thank you folks and feel free to do a excercise by clicking the clap button ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77bc1fbfee31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Rust’s Data Types]]></title>
            <link>https://medium.com/rustaceans/understanding-rusts-data-types-c33b9b6f8a89?source=rss-9f618953b580------2</link>
            <guid isPermaLink="false">https://medium.com/p/c33b9b6f8a89</guid>
            <category><![CDATA[data-type]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[rustlang]]></category>
            <dc:creator><![CDATA[Raunak]]></dc:creator>
            <pubDate>Mon, 15 Apr 2024 08:50:51 GMT</pubDate>
            <atom:updated>2024-04-23T13:08:50.385Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*i7CCJDeyAiOMhQzYU2gSeQ.jpeg" /></figure><h4>A Comprehensive Guide with Examples</h4><p>Rust is known for its strong emphasis on memory safety, concurrency, and performance. Central to Rust’s design philosophy is its rich set of data types, which enable developers to write efficient and safe code. In this article, we’ll discuss Rust’s fundamental data types along with illustrative examples to deepen your understanding.</p><ol><li>Primitive Data Types</li></ol><p>Rust provides several primitive data types, including integers, floating-point numbers, booleans, characters, and the unit type ().</p><ul><li><strong>Integers</strong></li></ul><p>Rust supports signed and unsigned integers of various sizes (8, 16, 32, 64, and arch), and selecting an appropriate size is important because it allows precise control over memory usage and arithmetic operations.</p><p>How you select the appropriate int size depends on the domain in which rust is going to be executed, Check out this <a href="https://users.rust-lang.org/t/use-of-integer-types-in-practice/54213/3"><strong>link</strong></a> to learn more about determining appropriate int size</p><p>For example</p><pre>let numb :i32 = 123;</pre><ul><li><strong>Floating-Point Numbers</strong></li></ul><p>Rust offers both single (f32) and double (f64) precision floating-point numbers. These are useful for representing decimal values.</p><pre>let flt:f32 = 3.14;</pre><ul><li><strong>Booleans</strong></li></ul><p>Booleans represent true or false values, which are essential for control flow and logical operations.</p><ul><li><strong>Characters</strong></li></ul><p>Rust’s char type represents a Unicode scalar value, allowing for internationalization and support for various scripts.</p><pre>let heart_emoji: char = &#39;❤&#39;;</pre><ul><li><strong>Unit Type</strong></li></ul><p>The unit type () is a special type with only one value, also denoted as an empty tuple. It&#39;s often used to indicate that a function does not return a meaningful value.</p><pre>fn print_hello() { println!(&quot;Hello, world!&quot;); }</pre><ol><li>Compound Data Types</li></ol><p>Rust also provides compound data types to aggregate multiple values into one.</p><ul><li><strong>Arrays</strong></li></ul><p>Arrays in Rust have a fixed size and hold elements of the same type.</p><pre>let numbers: [i32; 5] = [1, 2, 3, 4, 5]; // &quot;i32 determines the types.&quot;<br>// 5 determines the size <br>// array are homogenous i.e they only 1 type of data.</pre><ul><li><strong>Vectors</strong></li></ul><p>Vectors are very similar to arrays, but a great thing is that their sizes can be changed, i.e., more items can be pushed and existing items can be pulled.</p><p>The other time when vector is much worse is when you use a vector of vector vs a multidimensional array because each vector is allocated separately and lies all around memory which is not good for caching.</p><pre>let numberVec: Vec::new();<br>numberVec.push(1);<br>numberVec.push(2);</pre><p>Arrays and vectors both store data in a linear contiguous array, where accessing or iterating is both an O(1) operation, so there’s no difference in performance. The only case when vectors are slower is probably for some small lists because arrays are stored on the stack in the current stack frame hence, their data is highly probably already loaded to the CPU cache. Vector OTOH stores data on the heap so data will not be available in cache before they’re first accessed</p><p>Vector also has one more level of redirection because you need to load the address of the array first so the first memory access may also be slower, but that’s just negligible</p><p>The other time when vector is much worse is when you use a vector of vector vs a multidimensional array because each vector is allocated separately and lies all around memory, which is not good for caching.</p><ul><li><strong>Tuples</strong></li></ul><p>Tuples are collections of values of different types. They are useful when you want to combine a fixed number of heterogeneous data items.</p><pre>let mut person: (&amp;str, i32, bool) = (&quot;Alice&quot;, 30, &quot;UK&quot;);<br>  println!(&quot;Person details are {:?}&quot;, person); // original details<br>  person.1 = &quot;35&quot;;<br>  person.2 = &quot;USA&quot;;<br>  println!(&quot;Changed tuple = {:?}&quot;, person); // changed details<br><br><br>// tuples can be written dynamically as well<br>let mut mountain_heights = (&quot;Everest&quot;, 8848, &quot;Fishtail&quot;, 6993); <br>// here type definition is not given, directly values are combined into tuple.<br> println!(&quot;Original tuple = {:?}&quot;, mountain_heights);<br></pre><ol><li><strong>Custom Data Types</strong></li></ol><p>Rust enables developers to define their own data types using structs and enums.</p><ul><li><strong>Structs</strong></li></ul><p>Structs allow you to create custom data structures by grouping related data fields.</p><pre>struct Point {<br>  x: f64, <br>  y: f64 <br>};</pre><pre>let origin = Point { x: 0.0, y: 0.0 };</pre><ul><li><strong>Enums</strong></li></ul><p>Enums allow you to define a type by enumerating its possible variants.</p><pre>enum Direction {     <br>  Up,     <br>  Down,     <br>  Left,     <br>  Right, <br>};<br>  <br>let current_direction = Direction::Right;</pre><p>In conclusion, Rust’s diverse set of data types equips developers with powerful tools to build efficient and safe software. By understanding and leveraging these data types effectively, developers can write robust and reliable Rust code for a wide range of applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c33b9b6f8a89" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rustaceans/understanding-rusts-data-types-c33b9b6f8a89">Understanding Rust’s Data Types</a> was originally published in <a href="https://medium.com/rustaceans">Rustaceans</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Delving into Heaps: Unraveling the Secrets of Smart Data Structures]]></title>
            <link>https://medium.com/@raunakthakkar4/delving-into-heaps-unraveling-the-secrets-of-smart-data-structures-01b4307675fe?source=rss-9f618953b580------2</link>
            <guid isPermaLink="false">https://medium.com/p/01b4307675fe</guid>
            <category><![CDATA[dsa-training]]></category>
            <category><![CDATA[heap]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Raunak]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 20:16:58 GMT</pubDate>
            <atom:updated>2024-03-12T20:16:58.894Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xabb4Z8hRiv3HS3o" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Heaps, the wizards of computer science 🪄, wield their magic to simplify complex tasks. Let’s dive deep into their world, unpacking their secrets and uncovering the brilliance behind these remarkable data structures.</p><h3>The Heap: A Chill Hangout for Data 😁</h3><p>Imagine a laid-back hangout where everyone knows their spot—that’s a heap. It’s all about keeping things organized and breezy, ensuring easy access and manipulation of data.</p><h3>Highs and Lows: Max-Heaps vs Min-Heaps</h3><p>Heaps come in two flavors: max and min. Max-heaps are like skyscraper contests, where everyone’s vying for the top spot. Min-heaps, on the other hand, are more relaxed, with everyone content to hang out at the bottom. These variations cater to different needs, whether you’re prioritizing tasks or navigating a sea of possibilities.</p><h3>Magic Moves: Operations That Work Like a Charm</h3><p>Inserting, deleting, and heapifying—it’s like watching a magic show! These operations keep the heap in top-notch shape, effortlessly accommodating new additions and bidding farewell to departing friends. It’s all about maintaining the heap’s structure while ensuring smooth transitions.</p><h3>Real-World Coolness: Where Heaps Shine ✨</h3><p>Heaps are the unsung heroes of efficiency. <strong>They power priority queues, ensuring tasks are handled in order of importance. They’re the guiding lights of graph algorithms,</strong> helping navigate complex networks with ease. And when chaos reigns supreme, heap sort swoops in to bring order to the madness, sorting elements with lightning speed.</p><h3>Building Blocks: Easy-Peasy Implementations</h3><p>Implementing heaps is a breeze, whether you’re using arrays or linked structures. Arrays keep it simple, with elements lining up like soldiers in formation. Linked structures offer flexibility, allowing nodes to connect and groove to their own beat. It’s all about choosing the right tool for the job and crafting a heap that suits your needs.</p><h3>Let&#39;s take a look at the implementation of heap.</h3><p>So heap are not literally implemented in this way, but it’s an interpretation</p><pre><br>const myHeap = [];<br><br>function pushToMinHeap(heap, data) {<br>  heap?.push(data);<br>  let curr = heap?.length - 1;<br>  while (curr &gt; 0) {<br>    let parent = Math.floor((curr - 1) / 2); // accessing parent <br>    if (heap[curr] &lt; heap[parent]) {<br>      let temp = heap[parent];<br>      heap[parent] = heap[curr];<br>      heap[curr] = temp;<br>      curr = parent;<br>    } else {<br>      break;<br>    }<br>  }<br>}<br>function popFromMinHeap(heap, data) {<br>  // swap first and last element in heap<br>  // delete the last element (swapped)<br>  let newTempHead = heap[heap.length - 1]<br>  heap[heap.length - 1] = heap[0];<br>  heap[0] = newTempHead;<br>  heap.pop();<br>  let curr = 0;<br>  while ((2 * curr + 1) &lt; heap.length) {<br>    let indx = (2 * curr) + 2 &lt; heap.length &amp;&amp; heap[(2 * curr) + 2] &lt; heap[(2 * curr) + 1] ? (2 * curr) + 2 : (2 * curr) + 1<br>    console.log(indx);<br>    if (heap[indx] &lt; heap[curr]) {<br>      let newTempHead = heap[indx]<br>      heap[indx] = heap[curr];<br>      heap[curr] = newTempHead;<br>      curr = indx<br>    } else {<br>      break;<br>    }<br>  }<br>}<br><br>pushToMinHeap(myHeap, 2);<br>pushToMinHeap(myHeap, 1);<br>pushToMinHeap(myHeap, 4);<br>pushToMinHeap(myHeap, 0); // [1, 2, 4]<br>popFromMinHeap(myHeap);<br>pushToMinHeap(myHeap, 0); //[0, 1, 4, 2]<br>console.log(myHeap);</pre><p>This is a very naive implementation, but it helps us understand it’s core logic. In Javascript, heaps can be implemented using classes as well. Here’s a <a href="https://reintech.io/blog/understanding-implementing-heap-javascript"><strong>link</strong></a> to it.</p><p>So that’s it on heaps. If you want to know more about heaps and their types, drop a comment. Thanks for giving it a read and dropping a clap 👏🏻👏🏻 would help me write more of such articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01b4307675fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mutex Magic: Ensuring Thread Safety in Concurrent Programming in Rust]]></title>
            <link>https://medium.com/rustaceans/mutex-magic-ensuring-thread-safety-in-concurrent-programming-in-rust-c9bd487199c8?source=rss-9f618953b580------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9bd487199c8</guid>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[thread-safety]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <dc:creator><![CDATA[Raunak]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 13:22:07 GMT</pubDate>
            <atom:updated>2024-01-04T14:07:04.805Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*99-QX2Uvg2qkXbaUnwSVxA.png" /></figure><h4>Hello Everyone, Meet &quot;Mutex,” the cool-headed bouncer at the thread party, making sure everyone takes turns on the coding dance floor</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*BS0kl8NMoB_1hHgW9oPKOA.gif" /></figure><p>Get ready to groove as we unravel the beat behind Mutex in this tech-tango of synchronisation. Usage of mutex can easily backfire, i.e., the performance of an application can suffer a major hit if “mutex” is used wrongly.</p><p>Let&#39;s take a look at how the performance will be impacted. So Mutex is nothing but a structure that has been wrapped around critical data, and only the current accessing thread can modify it. There are mainly two operations that define its core functionality, and those are “lock” and &quot;unlock.”.</p><p>lock: when any incoming thread comes to edit the piece of data, that thread makes an attempt to take a lock, and if it successfully gets the lock, it has access to the data.</p><p>unlock: this operation can only be done by the thread that currently has access to the mutex. by doing this operation the current thread relases the lock that it has with itself and free’s the mutex so another threads can gain access and modify the data.</p><p>So the life cycle of mutex is like below:</p><ol><li>A thread tries to access the mutex by calling “lock” method</li><li>If the requesting thread gets the &quot;lock,&quot; it will have access to the data.</li><li>If not, the thread will wait for access.</li><li>Last but not least, once the work is done, the thread will release the lock, and Mutex will be free.</li></ol><p>So in a nutshell, this is how a mutex works, but there’s more that meets the eye, When many threads access the same of information, the locking needs to handled very neatly because there could be a case where two threads access mutex at same of point time, Now they try to obtain the lock and think that both of the threads have access to it, but this will bypass the main purpose of mutex.</p><p>To do operations at that speed and accuracy, we need the CPU’s help, which brings us to the concept of<a href="https://stackoverflow.com/questions/52196678/what-are-atomic-operations-for-newbies"> “atomic operations”</a>, These atomic operations are a set of functions that are defined within the OS (“compare-and-set” or “test-and-set”), and they help us solve the above-mentioned problem. These functions take some parameters, like</p><ul><li>where the value needs to be updated.</li><li>what value is to be updated.</li><li>What values will be compared?</li></ul><p>Using this atomic operation with the help of the CPU, we are now sure that no two threads will try to access the shared resource at the same point in time. But there’s one more important part which needs to be taken care of🤖🤖🤖</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FLF8plQNlgYwnK%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FLF8plQNlgYwnK%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExOHlkZGplYWRzbGUyYXdvZzk2d3R6YWwzZTgxN25zOWZ6bGdzN2RneSZlcD12MV9naWZzX2dpZklkJmN0PWc%2FLF8plQNlgYwnK%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="309" frameborder="0" scrolling="no"><a href="https://medium.com/media/507b57372695af5eb0e1124a95aff592/href">https://medium.com/media/507b57372695af5eb0e1124a95aff592/href</a></iframe><p>Yes, as we mentioned in the 3rd point, if mutex is already locked and another thread makes a request to mutex, the thread will wait until it gets the lock to mutex, so there’s a queue in which a thread waits until its turn comes to lock the mutex.</p><p>For a thread to wait, we again need the CPU’s help. The CPU has system calls that basically synchronise various threads and processes and give them the ability to wait.</p><p>So this basically sums up the implementation of mutex. Let&#39;s take a look at its usage in a programming language. We’ll use Rust for this purpose.</p><pre>use std::sync::Mutex;<br><br>pub fn myMutex(){<br>let counter =  Mutex::new(0); // created a mutex with value 0<br>let mut new_data = counter.lock().unwrap().add_assign(10);// accessing mutex&#39;s data and changing it by calling lock method<br>println(&quot;{:?}&quot;,new_data); // 10<br>} // Here, the `counter` variable goes out of scope, hence lock will be released.</pre><p>This is a very basic example, where just the main thread tries to access the mutex and updates the data. Also, you can find more methods available on <a href="https://doc.rust-lang.org/std/sync/struct.Mutex.html">mutex in rust</a>. To ensure thread safety, mutex is not the only way; there are many other ways we can ensure thread safety in Rust.</p><p>This brings us to end of the blog, A big shoutout to you guys for reading up until here. 😉</p><p>Stay curious!!!</p><h4>Rustaceans 🚀</h4><p>Thank you for being a part of the Rustaceans community! Before you go:</p><ul><li>Show your appreciation with a clap and follow the publication</li><li>Discover how you can contribute your own insights to <a href="https://medium.com/rustaceans/rustaceans-submissions-are-now-open-924e67cc595d"><strong><em>Rustaceans</em></strong></a></li><li>Connect with us: <a href="https://twitter.com/rustaceans_rs"><strong><em>X </em></strong></a>| <a href="https://substack.com/@rustbytes"><strong><em>Rust Bytes Newsletter</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9bd487199c8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rustaceans/mutex-magic-ensuring-thread-safety-in-concurrent-programming-in-rust-c9bd487199c8">Mutex Magic: Ensuring Thread Safety in Concurrent Programming in Rust</a> was originally published in <a href="https://medium.com/rustaceans">Rustaceans</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Module System In Rust]]></title>
            <link>https://medium.com/rustaceans/module-system-in-rust-427385412991?source=rss-9f618953b580------2</link>
            <guid isPermaLink="false">https://medium.com/p/427385412991</guid>
            <category><![CDATA[modules]]></category>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Raunak]]></dc:creator>
            <pubDate>Sun, 26 Nov 2023 11:16:41 GMT</pubDate>
            <atom:updated>2023-11-26T17:45:22.398Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bexDNFk4JJDsTl4BLMSEBA.jpeg" /></figure><p>We all know why modules are important for a developer and what are its advantages, So today we’ll be studying about modules in rust.</p><ol><li>How are modules built in Rust</li><li>How to import them in other places</li><li>And lastly we’ll also understand the how it works internally.</li></ol><p>A module in general is some collection of logical unit, that is managed separately. In rust-lang module is a collection of functions structs traits impl blocks and even other modules</p><p>In Rust modules are defined using the mod keyword followed module name and by-default they are private and to make them public you can use pub keyword</p><pre>// private module<br>mod my_first_mod{<br>fn private_function() {<br>        println!(&quot;called `my_mod::private_function()`&quot;);<br>    }<br>}<br><br>// public module<br>pub mod my_second_module{<br>pub fn  public_fn()  {<br>      println!(&quot;called `my_mod::public_function()`&quot;);<br>    }<br>}</pre><p>Modules can also be nested</p><pre>pub mod my_first_mod{<br>// public module<br>  pub mod my_second_module{<br>    pub fn  public_fn()  {<br>          println!(&quot;called `my_mod::public_function()`&quot;);<br>        }<br>  }<br>}</pre><p>To import module at other places, we have use keyword to the rescue !! with the help of use and as keyword we can import modules and use them at ease.</p><pre>// front_of_house.rs<br>mod front_of_house {<br>    pub mod hosting {<br>        pub fn add_to_waitlist() {}<br>    }<br>}<br><br>// eat_at_res.rs<br>use crate::front_of_house::hosting;<br><br>pub fn eat_at_restaurant() {<br>    hosting::add_to_waitlist();<br>}</pre><p>as we can see that add_to_waitlist is called from another file that is “eat_at_res.rs” on the 1st line we have used “use” keyword to import the “front_of_house.rs” module.</p><p>With “as” keyword things get little bit easier, because with “as” keyword we can rename the module in given scope, an example is shown below.</p><pre>// eat_at_res.rs<br>use crate::front_of_house::hosting as hosting_module;<br><br>pub fn eat_at_restaurant() {<br>    hosting_module::add_to_waitlist();<br>}<br><br>// front_of_house.rs<br>mod front_of_house {<br>    pub mod hosting {<br>        pub fn add_to_waitlist() {}<br>    }<br>}</pre><p>Lastly, we’ll see how modules in Rust are different from modules present in other languages, That is because the modules are not bound to the ‘File system,’ meaning they are independent of their file locations, allowing the code to reside anywhere.</p><p>But it is suggested to have specific files as per some programming patterns, even the Rust foundation saw its need and later started supported some patterns such as, rust will always search for a folder and file with .rs extension or module_name with .rs extension</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*MTgXMhgcEk14-zJa_KHA2g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=427385412991" width="1" height="1" alt=""><hr><p><a href="https://medium.com/rustaceans/module-system-in-rust-427385412991">Module System In Rust</a> was originally published in <a href="https://medium.com/rustaceans">Rustaceans</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Function.prototype.bind]]></title>
            <link>https://medium.com/@raunakthakkar4/javascript-function-prototype-bind-8a1465503b65?source=rss-9f618953b580------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a1465503b65</guid>
            <category><![CDATA[function-binding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[binding]]></category>
            <dc:creator><![CDATA[Raunak]]></dc:creator>
            <pubDate>Wed, 01 Nov 2023 12:35:22 GMT</pubDate>
            <atom:updated>2023-11-01T12:35:22.861Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RtAYUzRWyBcL0MQHssHEBw.jpeg" /><figcaption>formal binding.</figcaption></figure><p>Hello Family, It has been some time since I wrote an article on JS, Since i am learning rust and core- features, here are some articles that i wrote about RUST</p><ul><li><a href="https://medium.com/@raunakthakkar4/iterators-in-programming-and-implementation-ways-in-rust-f6abf5b2d764">Iterators in Programming and implementation ways in Rust🦀</a></li><li><a href="https://medium.com/@raunakthakkar4/hey-guys-this-is-my-first-article-on-rust-and-in-this-i-will-be-talking-about-lifetimes-d4e4370c5dac">LifeTimes in Rust</a></li></ul><p>So coming back to JS and while brushing up on JS concepts, I read, Function.prototype.bind()and this time it blew my mind. 🤯🤯🤯, initiallly when I understood bind i could only understand that bind returns a Function with provided context .</p><pre>// object definition<br>const student1 = {<br>  name: &quot;Jack&quot;,<br>  grade: &quot;5&quot;,<br>  introduction: function () {<br>    console.log(this.name + &quot;studies in grade&quot; + this.grade + &quot;.&quot;);<br>  },<br>};</pre><pre>// object definition<br>const student2 = {<br>  name: &quot;Jimmy &quot;,<br>  grade: &quot; 6&quot;,<br>};</pre><pre>The object of student 2 is to borrow the introduction method from student1<br>let result= student1.introduction.bind(student2);</pre><p>In the above example, when we call bind with student2 and it being the context provided. to bind and we get a function result that is called</p><pre>// invoking introduction() function<br>result();</pre><pre>// Output:<br>Jimmy studies in grade 6.</pre><p>We get the above output, so as we can see, the name “Jimmy” and grade “6” are part of student object. So in this way, “bind” generally works.</p><p>now the part that blew my mind 💣🤯</p><p><strong>Another use case is to give some parameters to “bind,” and the returned function could be called from anywhere.</strong></p><pre>function fn(...args) {<br>  console.log(&quot;here&quot;, args);<br>}</pre><pre>const one = fn.bind(this, ...[1, 2, 3, 4]);</pre><pre>console.log(one()); // o/p here (4) [1, 2, 3, 4]</pre><p>As you can see, itone is just called without any arguments, but still, in the console, we would be able to see “here (4) [1, 2, 3, 4]” as the output. But how? 🤔🧐.</p><p>That is because “bind” returns a new “bound function.” The bound function will store the parameters passed—which include the value ofthis and the first few arguments—as its internal state.</p><p>Conclusion: <strong>Function.Bind is an extremely powerful function that not only calls itself on a specific context but also keeps arguments (initially passed) to itself. If any other argument is passed on to the bound function, it also respects that.</strong></p><p>So that’s it for today, and I hope you enjoyed this article.</p><p>PS: You can use the concept of binding in Javascript currying. <a href="https://bigfrontend.dev/problem/implement-curry">https://bigfrontend.dev/problem/implement-curry</a> and another important question would be a <a href="https://medium.com/@shyamtayal/lets-write-a-polyfill-for-bind-ac601290aab7">polyfill of Function.prototype.bind</a>.</p><p>If you’re reading this to this extent, you deserve a chocolate 🍫</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a1465503b65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Iterators in Programming and implementation ways in Rust]]></title>
            <link>https://medium.com/@raunakthakkar4/iterators-in-programming-and-implementation-ways-in-rust-f6abf5b2d764?source=rss-9f618953b580------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6abf5b2d764</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[iterators]]></category>
            <category><![CDATA[rustlang]]></category>
            <category><![CDATA[rustling]]></category>
            <dc:creator><![CDATA[Raunak]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 13:45:01 GMT</pubDate>
            <atom:updated>2023-10-25T13:45:01.996Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tVAKjyyWqsYD3oy7yH9kyA.png" /><figcaption>This is Krabby and its a Pokèmon.</figcaption></figure><h3>Iterators in Programming and implementation ways in Rust 🦀</h3><p>Iterators were introduced in 1974, and they’re somewhat like database cursors [in simple words, a cursor is a pointer-like data structure that traverses over database records]. So are iterators, but iterators are more flexible in nature. Iterators are basically applied to containers [containers are array-like or list-like structures that have collections of objects].</p><p>I know I know one question of your’s would be, are they different from loops 🤔 ?</p><p>And the answer to that would be, drum rolls 🥁🥁🥁</p><p>Yes, it is. Because iterators give control of flow to the developer, i.e., unless a developer does not want the next iteration to take place, it will not happen. Unlike looping, which does not provide that, loops complete the number of given iterations and then proceed ahead.</p><p>We’ll see some examples of it later in the article.</p><p>Iterator in Rust comes from the<strong> ‘Iterator’</strong> trait; it is not the only trait that consists of the implementation of iterator; there are other traits as well.</p><p>For Eg:</p><ul><li><a href="https://doc.rust-lang.org/std/iter/trait.IntoIterator.html#">IntoIterator</a> : This trait comes into play when we use .into_iter() , i.e to take ownership of any collection and return a new iterator that is mutable</li><li><a href="https://doc.rust-lang.org/std/iter/trait.FromIterator.html#">FromIterator</a> : This this Trait comes into play when we give any iterator to a for loop to do an operation</li></ul><p>To create an iterator in Rust, there are 3 methods <strong>.iter()</strong> , <strong>.into_iter()</strong> , <strong>.iter_mut()</strong> .</p><p>.iter()This method refers to an applied collection and returns an iterator with references to elements present in the collection, for example.</p><pre>Let v1 = vec![1, 2, 3]; // creates a vector<br>let v1_iter = v1.iter(); // uses the iter() method to create a itertor <br>                             // with references of [&amp;1, &amp;2, &amp;3]</pre><p>.into_iter()→ this method consumes (takes ownership of) an applied collection and returns an iterator with elements present in the collection, for example.</p><pre>Let v1 = vec![1, 2, 3]; // creates a vector<br>let v1_iter = v1.into_iter(); // uses the iter() method to create a itertor <br>                             // with references of [1, 2, 3]</pre><p>.iter_mut()This method refers to an applied collection and returns an iterator with mutable references to elements present in the collection, for example.</p><pre>Let v1 = vec![1, 2, 3]; // creates a vector<br>let mut v1_iter = v1.into_iter(); // uses the iter() method to create a itertor <br>                             // with references of [&amp;mut 1, &amp;mut 2, &amp;mut 3]</pre><p>Using the above methods, we can create an iterator in Rust. Now we shall talk about consuming or using them in our code. Iterators have many methods. Check out the <a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html">list of methods</a> present on iterators, some of which we’ll discuss here.</p><ul><li><strong>iter.next()</strong>: Advances the iterator and returns the next value.Returns <a href="https://doc.rust-lang.org/std/option/enum.Option.html#variant.None">None</a> when iteration is finished.</li><li><strong>iter.count()</strong>: This method will call <a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next">next</a> repeatedly until <a href="https://doc.rust-lang.org/std/option/enum.Option.html#variant.None">None</a> is encountered, returning the number of times it has <a href="https://doc.rust-lang.org/std/option/enum.Option.html#variant.Some">Some</a>seen Note that <a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next">next</a> has to be called at least once, even if the iterator does not have any elements.</li><li><strong>iter.last()</strong>: This method will evaluate the iterator until it returns<a href="https://doc.rust-lang.org/std/option/enum.Option.html#variant.None">None</a>. While doing so, it keeps track of the current element. After <a href="https://doc.rust-lang.org/std/option/enum.Option.html#variant.None">None</a> is returned, last() will then return the last element it saw.</li></ul><p>At last, we can conclude how iterators are implemented in rust and in what different ways we can use them. We could also see a glimpse of the methods that come with iterators in Rust.</p><p>Thank you for reading this article, and until next time keep rusting.. 🦀🦀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6abf5b2d764" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LifeTimes in Rust]]></title>
            <link>https://medium.com/@raunakthakkar4/hey-guys-this-is-my-first-article-on-rust-and-in-this-i-will-be-talking-about-lifetimes-d4e4370c5dac?source=rss-9f618953b580------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4e4370c5dac</guid>
            <dc:creator><![CDATA[Raunak]]></dc:creator>
            <pubDate>Mon, 03 Jul 2023 19:17:40 GMT</pubDate>
            <atom:updated>2023-07-03T19:52:49.820Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q7pqjUTllN7BAc2FZ1LVpA.jpeg" /></figure><p>LifeTimes in Rust</p><p>Hey Guys, This is my first article on RUST and in this, I will be talking about **lifetimes**.</p><p>TLDR, lifetime is something that denotes the lifetime of a value using a generic value.</p><p>according to the [documentation](<a href="https://doc.rust-lang.org/rust-by-example/scope/lifetime.html):-">https://doc.rust-lang.org/rust-by-example/scope/lifetime.html):-</a> “A *lifetime* is a construct of the compiler (or more specifically, its *borrow checker*) which uses to ensure all borrows are valid. A variable’s lifetime begins when it is created and ends when it is destroyed in a scope”</p><p>The main aim of “lifetimes” in Rust is to prevent *dangling references*, “dangling references and wild references are **references/pointers that do not resolve to a valid destination**”</p><p>for eg</p><pre>fn main() { <br>let x;<br>  { // a new scope starts<br><br>    let y = 5;<br>    x= &amp;y; // passing a reference of &#39;x&#39; to y;<br><br>  }// scope ends<br>println!(&quot;x: {}&quot;, x); <br>}`</pre><p>the output for the above code is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*gITS_v6BRNuA7hg1_oJofg.png" /></figure><p>here as we can see that as the variable y will not be accessible as the inner scope ends. hence the inner scope is the lifetime of variable ‘y’.</p><p>The lifetime can be expressed in rust using 2 ways</p><ol><li>explicitly (annotation) :- lifetime can be annotated using generics, hence it can be used with “functions”, “Traits”, “Methods”, “Structs”, and “Bounds”</li><li>implicitly (elision) :- lifetime can be simply elided as the lifetime which borrower-checked gets is a simple and a straight forward pattern.</li></ol><p>Function:- In functions lifetimes can be annotated as well as elided, but there are some precautions to be followed when using lifetimes in the functions, otherwise can lead to failure of program at compile time.</p><p>“any reference being returned <em>must</em> have the same lifetime as an input or be static.”</p><p>“a function can be given multiple lifetimes but using a single lifetime annotation increases readability ”</p><pre>fn print_multi&lt;&#39;a, &#39;b&gt;(x: &amp;&#39;a i32, y: &amp;&#39;b i32) {<br>    println!(&quot;`print_multi`: x is {}, y is {}&quot;, x, y);<br>}<br><br>fn main() {<br>    let x = 7;<br>    let y = 9;<br> <br>    print_multi(&amp;x, &amp;y);<br>}</pre><p>Lifetime works same with “Traits” “Methods” and “Structs”</p><p>on the other hand, “Bounds” are treated differently. to bound it we need to use “+” character</p><pre>fn print_ref&lt;&#39;a, T&gt;(t: &amp;&#39;a T) where<br>    T: Debug + &#39;a {<br>    println!(&quot;`print_ref`: t is {:?}&quot;, t);<br>}</pre><p>There’s one special type of lifetime in rust, that is “static”, it is a lifetime that stays through-out the program. Generally to create a variable with static lifetime is to create it with using static keyword.</p><pre>static NUM: i32 = 18;<br>let s: &amp;&#39;static str = &quot;hello world&quot;;</pre><p>Final Notes</p><p>Lifetime is a very subtle feature that allows us to understand the flow of a program and it is very different than scopes in Rust. In the next article i will be discussing about Scopes and we can compare how they’re different from lifetimes.</p><p>Also if you liked this article please show some love to it and follow me on <a href="https://www.linkedin.com/in/raunakthakkar/">LinkedI</a>n, and Thank you for reading along.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4e4370c5dac" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>