<?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"><channel><title><![CDATA[Untitled Publication]]></title><description><![CDATA[Untitled Publication]]></description><link>https://siddharthqs.com</link><generator>RSS for Node</generator><lastBuildDate>Tue, 19 May 2026 13:16:29 GMT</lastBuildDate><atom:link href="https://siddharthqs.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Mastering Iterators: Comprehensive Insights You Need]]></title><description><![CDATA[Iterators are a fundamental concept in programming that enable you to process a sequence of items, such as elements in a collection, one at a time, without revealing the collection's internal structure. They form the backbone of operations like loopi...]]></description><link>https://siddharthqs.com/mastering-iterators-comprehensive-insights-you-need</link><guid isPermaLink="true">https://siddharthqs.com/mastering-iterators-comprehensive-insights-you-need</guid><category><![CDATA[iterator]]></category><category><![CDATA[Rust]]></category><category><![CDATA[Functional Programming]]></category><dc:creator><![CDATA[Siddharth]]></dc:creator><pubDate>Sun, 23 Mar 2025 02:30:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/aaSDzr-ou5Y/upload/edd1b0224a5e0e653aaac21a4343af9b.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Iterators</strong> are a fundamental concept in programming that enable you to process a sequence of items, such as elements in a collection, one at a time, without revealing the collection's internal structure. They form the backbone of operations like looping, filtering, and mapping over collections. When you encounter constructs like these, you can liken them to functional or stream-based idioms found in languages such as C# or Java.</p>
<p>When you see something like:</p>
<pre><code class="lang-rust">collection.iter()
    .map(...)
    .filter(...)
    .take(...)
    .collect();
</code></pre>
<p><strong>Why Iterators Are Useful</strong></p>
<ul>
<li><p><strong>Abstraction</strong>: They hide the underlying container’s implementation. You don’t need to know if it’s an array, a linked list, or some more specialized structure.</p>
</li>
<li><p><strong>Safety / Encapsulation</strong>: With an iterator, you typically avoid directly indexing into a collection’s memory. This reduces off-by-one errors, out-of-bounds errors, or concurrency issues.</p>
</li>
<li><p><strong>Composability</strong>: Iterators can be transformed, filtered, and combined to express complex operations in a clean, functional style.</p>
</li>
</ul>
<h1 id="heading-iterators-in-rust">Iterators in Rust</h1>
<p>Rust’s iterator system is powerful and versatile, offering developers a robust toolset for managing collections efficiently. It simplifies the code and reduces the potential for errors. This not only makes the code more readable but also aligns with functional programming paradigms, making it easier for developers familiar with languages like C# or Java to adapt.</p>
<ol>
<li><p><strong>They Are Lazy</strong></p>
<ul>
<li><p>In Rust, when you call methods like <code>.map()</code>, <code>.filter()</code>, or <code>.take()</code> on an iterator, it does not immediately create a new collection. Instead, these methods return a <em>new iterator</em> that, when advanced, processes items on demand.</p>
</li>
<li><p>This means you can build up chained iterator calls without incurring overhead until you actually consume the iterator (e.g., in a for loop, or when calling a terminal method like <code>.collect()</code>).</p>
</li>
</ul>
</li>
<li><p><strong>Three Main “Iterator” Traits</strong></p>
<ul>
<li><p><code>Iterator</code>: The trait for iterators that produce items by value. Typically you implement this when you want to define how to produce a sequence of items.</p>
</li>
<li><p><code>IntoIterator</code>: For types (like <code>Vec</code>, slices, and so on) that can be converted into an iterator.</p>
</li>
<li><p><code>DoubleEndedIterator</code>: An extension that allows “reverse” iteration (calling <code>.next_back()</code> in addition to <code>.next()</code> from the front).</p>
</li>
</ul>
</li>
<li><p><strong>Ownership, Borrowing, and Lifetimes</strong></p>
<ul>
<li><p>Rust’s type system enforces rules to ensure safety. For iterators, this means that when you iterate over a collection, either you move (take ownership of) the collection or you borrow from it in a well-defined way.</p>
</li>
<li><p><code>iter()</code> borrows each element by reference.</p>
</li>
<li><p><code>into_iter()</code> consumes (takes ownership of) the elements, so the iterator yields the items by value.</p>
</li>
<li><p><code>iter_mut()</code> borrows each element mutably, allowing you to modify items in place.</p>
</li>
</ul>
</li>
<li><p><strong>Common Methods</strong></p>
<ul>
<li><p><code>map(f)</code>: Apply a function <code>f</code> to each item.</p>
</li>
<li><p><code>filter(pred)</code>: Keep only items where <code>pred(item)</code> is <code>true</code>.</p>
</li>
<li><p><code>fold(init, f)</code>: Accumulate items into a single value, starting from <code>init</code>, applying <code>f</code> in a fold/reduction manner.</p>
</li>
<li><p><code>collect()</code>: Consume an iterator and gather the items into a collection (like a <code>Vec</code>, <code>HashSet</code>, etc.).</p>
</li>
<li><p><code>take(n)</code>, <code>skip(n)</code>, <code>enumerate()</code>, etc.: Additional combinators for slicing, offset, or enumerating.</p>
</li>
</ul>
</li>
<li><p><strong>Consuming vs. Adapting Iterators</strong><br /> In Rust’s library documentation, you might see a distinction between “consuming” vs. “adapting” iterators:</p>
<ul>
<li><p><strong>Consuming</strong>: These methods take ownership of the iterator to produce a final value or another data structure (e.g., <code>collect()</code>, <code>fold()</code>). Once consumed, the iterator cannot be used again.</p>
</li>
<li><p><strong>Adapting</strong>: These methods produce a <em>new</em> iterator (e.g., <code>map</code>, <code>filter</code>). These can be chained before any final consumption.</p>
</li>
</ul>
</li>
</ol>
<h2 id="heading-examples"><strong>Examples</strong></h2>
<p>Below is some "cookbook"-style collection of <strong>common and practical iterator patterns</strong> in Rust. This will help you become more comfortable and familiar with iterators, allowing you to later explore them in greater depth.</p>
<h3 id="heading-1-iterate-and-collect-into-a-new-vector">1. <strong>Iterate and Collect into a New Vector</strong></h3>
<p>A basic example: transform and collect.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">example_collect</span></span>() {
    <span class="hljs-keyword">let</span> numbers = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
    <span class="hljs-comment">// Double each number and collect into a new Vec&lt;i32&gt;</span>
    <span class="hljs-keyword">let</span> doubled: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt; = numbers.iter().map(|x| x * <span class="hljs-number">2</span>).collect();
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, doubled); <span class="hljs-comment">// Output: [2, 4, 6, 8, 10]</span>
}
</code></pre>
<p><code>iter()</code> borrows each element (so <code>x</code> is <code>&amp;i32</code>). <code>map(|x| x * 2)</code> applies a function to each element. <code>|x| x * 2</code> is closure. <code>collect()</code> finalizes the lazy chain, producing the <code>Vec&lt;i32&gt;</code>.</p>
<hr />
<h3 id="heading-2-filter-items-based-on-a-condition">2. <strong>Filter Items Based on a Condition</strong></h3>
<p>Use <code>filter</code> to keep only items meeting a criterion.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">example_filter</span></span>() {
    <span class="hljs-keyword">let</span> numbers = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">10</span>, <span class="hljs-number">15</span>, <span class="hljs-number">20</span>, <span class="hljs-number">25</span>, <span class="hljs-number">30</span>];
    <span class="hljs-comment">// Keep only multiples of 10</span>
    <span class="hljs-keyword">let</span> multiples_of_ten: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt; = numbers
        .into_iter()        <span class="hljs-comment">// Now x is i32, not &amp;i32</span>
        .filter(|x| x % <span class="hljs-number">10</span> == <span class="hljs-number">0</span>)
        .collect();

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, multiples_of_ten); <span class="hljs-comment">// Output: [10, 20, 30]</span>
}
</code></pre>
<p><code>into_iter()</code> consumes <code>numbers</code> and yields <code>i32</code> (by value). <code>filter(...)</code> returns a new iterator keeping only those items where the predicate is true.</p>
<hr />
<h3 id="heading-3-filter-and-map-in-one-step-filtermap">3. <strong>Filter and Map in One Step:</strong> <code>filter_map</code></h3>
<p>Sometimes you want to transform items and discard certain items altogether. <code>filter_map</code> combines <code>filter</code> and <code>map</code> in one step, working with <code>Option</code>.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> inputs = <span class="hljs-built_in">vec!</span>[<span class="hljs-string">"42"</span>, <span class="hljs-string">"93"</span>, <span class="hljs-string">"hello"</span>, <span class="hljs-string">"128"</span>, <span class="hljs-string">"xyz"</span>];
<span class="hljs-comment">// Try parsing each string as an integer.</span>
<span class="hljs-comment">// If successful, keep the integer; otherwise, skip.</span>
<span class="hljs-keyword">let</span> parsed: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt; = inputs
        .iter()
        .filter_map(|s| s.parse::&lt;<span class="hljs-built_in">i32</span>&gt;().ok())
        .collect();
<span class="hljs-comment">// parsed: [42, 93, 128]</span>
</code></pre>
<p><code>s.parse::&lt;i32&gt;().ok()</code> returns <code>Some(i32)</code> if parse succeeded, or <code>None</code> otherwise. <code>filter_map</code> only yields <code>Some</code> items.</p>
<hr />
<h3 id="heading-4-combine-multiple-iterators-chain">4. <strong>Combine Multiple Iterators:</strong> <code>chain</code></h3>
<p>Use <code>chain</code> to create a single iterator that yields items from two or more sources sequentially.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> nums1 = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">let</span> nums2 = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>];
<span class="hljs-keyword">let</span> chained: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt; = nums1
        .into_iter()
        .chain(nums2.into_iter())
        .collect();
<span class="hljs-comment">// chained: [1, 2, 3, 4, 5, 6]</span>
</code></pre>
<p><code>chain</code> takes two iterators and iterates over the first fully, then the second. In this example, <code>nums1</code> and <code>nums2</code> are both consumed (moved) by <code>into_iter()</code>.</p>
<hr />
<h3 id="heading-5-enumerate-items-with-enumerate">5. <strong>Enumerate Items with</strong> <code>enumerate</code></h3>
<p>Sometimes you need both the index and the value.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> animals = <span class="hljs-built_in">vec!</span>[<span class="hljs-string">"cat"</span>, <span class="hljs-string">"dog"</span>, <span class="hljs-string">"bird"</span>];
<span class="hljs-keyword">for</span> (index, animal) <span class="hljs-keyword">in</span> animals.iter().enumerate() {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}: {}"</span>, index, animal);
}
<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// 0: cat</span>
<span class="hljs-comment">// 1: dog</span>
<span class="hljs-comment">// 2: bird</span>
</code></pre>
<p><code>enumerate()</code> yields <code>(index, item)</code> pairs. The <code>index</code> starts at 0 by default.</p>
<hr />
<h3 id="heading-6-find-the-first-matching-item-find">6. <strong>Find the First Matching Item:</strong> <code>find</code></h3>
<p>The <code>find</code> method returns the first item that satisfies a condition (as an <code>Option</code>).</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> numbers = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">7</span>, <span class="hljs-number">9</span>];
<span class="hljs-comment">// Find the first number that is divisible by 3</span>
<span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Some</span>(found) = numbers.iter().find(|&amp;&amp;x| x % <span class="hljs-number">3</span> == <span class="hljs-number">0</span>) {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Found: {}"</span>, found); <span class="hljs-comment">// Output: Found: 3</span>
} <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"No match found"</span>);
}
</code></pre>
<p><code>find</code> stops searching after the first match. Returns <code>None</code> if no match is found.</p>
<hr />
<h3 id="heading-7-take-while-a-condition-is-true-takewhile">7. <strong>Take While a Condition is True:</strong> <code>take_while</code></h3>
<p>Use <code>take_while</code> to yield items only as long as a predicate holds. (Note: This is available via <code>Iterator::take_while</code> in stable Rust 1.52+.)</p>
<pre><code class="lang-rust">    <span class="hljs-keyword">let</span> numbers = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>, <span class="hljs-number">10</span>, <span class="hljs-number">1</span>, <span class="hljs-number">12</span>];
    <span class="hljs-comment">// Take only even numbers until we reach the first odd</span>
    <span class="hljs-keyword">let</span> evens_up_to_odd: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt; = numbers
        .into_iter()
        .take_while(|x| x % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>)
        .collect();

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, evens_up_to_odd); <span class="hljs-comment">// Output: [2, 4, 6, 8, 10]</span>
</code></pre>
<p>Once <code>take_while</code> sees a value that doesn’t satisfy the predicate, it stops altogether.</p>
<hr />
<h3 id="heading-8-accumulatingreducing-fold">8. <strong>Accumulating/Reducing:</strong> <code>fold</code></h3>
<p>Use <code>fold</code> to accumulate values into a single result. This is often used for sums, products, or more advanced aggregations.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">example_fold</span></span>() {
    <span class="hljs-keyword">let</span> numbers = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

    <span class="hljs-keyword">let</span> sum = numbers.iter().fold(<span class="hljs-number">0</span>, |acc, &amp;x| acc + x);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Sum is {}"</span>, sum); <span class="hljs-comment">// Output: 15</span>

    <span class="hljs-keyword">let</span> product = numbers.iter().fold(<span class="hljs-number">1</span>, |acc, &amp;x| acc * x);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Product is {}"</span>, product); <span class="hljs-comment">// Output: 120</span>
}
</code></pre>
<p>The first argument to <code>fold</code> is the initial accumulator value. The closure receives the accumulator and the next item.</p>
<hr />
<h3 id="heading-9-partition-items-into-two-groups-partition">9. <strong>Partition Items into Two Groups:</strong> <code>partition</code></h3>
<p><code>partition</code> splits items into two collections based on a condition, returning <code>(Vec&lt;T&gt;, Vec&lt;T&gt;)</code>.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">example_partition</span></span>() {
    <span class="hljs-keyword">let</span> numbers = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>];

    <span class="hljs-keyword">let</span> (even, odd): (<span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt;, <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt;) = numbers
        .into_iter()
        .partition(|x| x % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>);

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Even: {:?}"</span>, even); <span class="hljs-comment">// Even: [2, 4, 6]</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Odd: {:?}"</span>, odd);   <span class="hljs-comment">// Odd: [1, 3, 5]</span>
}
</code></pre>
<p>The first <code>Vec</code> collects items where the predicate is true, and the second collects items where it is false.</p>
<hr />
<h3 id="heading-10-zip-two-iterators-together-zip">10. <strong>Zip Two Iterators Together:</strong> <code>zip</code></h3>
<p><code>zip</code> pairs items from two iterators into <code>(item1, item2)</code> tuples.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">example_zip</span></span>() {
    <span class="hljs-keyword">let</span> letters = <span class="hljs-built_in">vec!</span>[<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>];
    <span class="hljs-keyword">let</span> numbers = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];

    <span class="hljs-comment">// Zip together into pairs</span>
    <span class="hljs-keyword">let</span> zipped: <span class="hljs-built_in">Vec</span>&lt;(<span class="hljs-built_in">char</span>, <span class="hljs-built_in">i32</span>)&gt; = letters.into_iter().zip(numbers).collect();
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, zipped); <span class="hljs-comment">// Output: [('a', 1), ('b', 2), ('c', 3)]</span>
}
</code></pre>
<p>The iteration stops when the shortest iterator ends. In this example, <code>letters</code> has 3 items, <code>numbers</code> has 4, so only 3 pairs are created.</p>
<hr />
<h3 id="heading-11-flatten-an-iterator-of-iterators-flatten">11. <strong>Flatten an Iterator of Iterators:</strong> <code>flatten</code></h3>
<p>If you have nested iterators (e.g., a <code>Vec&lt;Vec&lt;T&gt;&gt;</code>), you can flatten it into a single sequence.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">example_flatten</span></span>() {
    <span class="hljs-keyword">let</span> nested = <span class="hljs-built_in">vec!</span>[<span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>], <span class="hljs-built_in">vec!</span>[<span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>], <span class="hljs-built_in">vec!</span>[<span class="hljs-number">6</span>]];
    <span class="hljs-keyword">let</span> flattened: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt; = nested.into_iter().flatten().collect();

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, flattened); <span class="hljs-comment">// Output: [1, 2, 3, 4, 5, 6]</span>
}
</code></pre>
<p><code>flatten</code> automatically iterates through each sub-iterator/item. You can also use <code>flat_map</code> if you need to transform and flatten in one step.</p>
<hr />
<h3 id="heading-12-skipping-elements-or-taking-a-specific-count-skip-take">12. <strong>Skipping Elements or Taking a Specific Count:</strong> <code>skip</code> / <code>take</code></h3>
<p>Use <code>skip</code> to ignore a certain number of items, <code>take</code> to limit iteration to a certain count.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">example_skip_take</span></span>() {
    <span class="hljs-keyword">let</span> numbers = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>, <span class="hljs-number">40</span>, <span class="hljs-number">50</span>, <span class="hljs-number">60</span>];

    <span class="hljs-comment">// Skip the first 2, then take the next 3</span>
    <span class="hljs-keyword">let</span> slice: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt; = numbers
        .iter()
        .skip(<span class="hljs-number">2</span>)
        .take(<span class="hljs-number">3</span>)
        .copied()  <span class="hljs-comment">// because we had .iter() -&gt; &amp;i32</span>
        .collect();

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, slice); <span class="hljs-comment">// Output: [30, 40, 50]</span>
}
</code></pre>
<p><code>skip(n)</code> ignores the first <code>n</code> items. <code>take(n)</code> yields only the next <code>n</code> items, then stops. <code>.copied()</code> turns <code>&amp;i32</code> into <code>i32</code>; you could also use <code>.cloned()</code> or just leave them as references if that’s acceptable.</p>
<h1 id="heading-intoiterator-trait">IntoIterator Trait</h1>
<p><code>IntoIterator</code> is a trait that defines how a type can be converted into an iterator. It's one of the fundamental traits in Rust's collections and iteration system.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">IntoIterator</span></span> {
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Item</span></span>;
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">IntoIter</span></span>: <span class="hljs-built_in">Iterator</span>&lt;Item = Self::Item&gt;;

    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">into_iter</span></span>(<span class="hljs-keyword">self</span>) -&gt; Self::IntoIter;
}
</code></pre>
<p>This trait has three key components:</p>
<ul>
<li><p><code>Item</code>: The type of item that the iterator will produce</p>
</li>
<li><p><code>IntoIter</code>: The specific iterator type that will be returned</p>
</li>
<li><p><code>into_iter()</code>: The method that consumes the collection and returns an iterator.</p>
</li>
</ul>
<h2 id="heading-how-intoiterator-is-used">How IntoIterator Is Used</h2>
<p><strong>For loops</strong>: When you write a <code>for</code> loop in Rust, the compiler automatically calls into_iter() on the collection you're iterating over:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">for</span> element <span class="hljs-keyword">in</span> collection {
    <span class="hljs-comment">// This is actually doing: for element in collection.into_iter() { ... }</span>
}
</code></pre>
<p>When you write a <code>for</code> loop or manually call <code>collection.into_iter()</code>, Rust decides <strong>which implementation</strong> to call based on whether you’re iterating over the collection by value (<code>collection.into_iter()</code>), by reference (<code>(&amp;collection).into_iter()</code>), or by mutable reference (<code>(&amp;mut collection).into_iter()</code>).</p>
<p><strong>Converting collections to iterators</strong>:</p>
<p>You can explicitly call into_iter() to convert a collection into an iterator:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> vec = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">let</span> iter = vec.into_iter(); <span class="hljs-comment">// Consumes vec, returns an iterator</span>
</code></pre>
<h2 id="heading-different-implementations">Different Implementations</h2>
<p>Most collections in Rust implement <code>IntoIterator</code> in multiple ways:</p>
<p><strong>For the collection itself (by value)</strong>: Consumes the collection, returning an iterator that takes ownership of the elements:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span>&lt;T&gt; <span class="hljs-built_in">IntoIterator</span> <span class="hljs-keyword">for</span> <span class="hljs-built_in">Vec</span>&lt;T&gt; {
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Item</span></span> = T;
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">IntoIter</span></span> = std::vec::IntoIter&lt;T&gt;;

    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">into_iter</span></span>(<span class="hljs-keyword">self</span>) -&gt; Self::IntoIter { <span class="hljs-comment">/* ... */</span> }
}
</code></pre>
<p><strong>For references to the collection (&amp;)</strong>: Creates an iterator that borrows the elements:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span>&lt;<span class="hljs-symbol">'a</span>, T&gt; <span class="hljs-built_in">IntoIterator</span> <span class="hljs-keyword">for</span> &amp;<span class="hljs-symbol">'a</span> <span class="hljs-built_in">Vec</span>&lt;T&gt; {
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Item</span></span> = &amp;<span class="hljs-symbol">'a</span> T;
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">IntoIter</span></span> = std::slice::Iter&lt;<span class="hljs-symbol">'a</span>, T&gt;;

    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">into_iter</span></span>(<span class="hljs-keyword">self</span>) -&gt; Self::IntoIter { <span class="hljs-comment">/* ... */</span> }
}
</code></pre>
<p><strong>For mutable references (&amp;mut)</strong>: Creates an iterator that mutably borrows the elements:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span>&lt;<span class="hljs-symbol">'a</span>, T&gt; <span class="hljs-built_in">IntoIterator</span> <span class="hljs-keyword">for</span> &amp;<span class="hljs-symbol">'a</span> <span class="hljs-keyword">mut</span> <span class="hljs-built_in">Vec</span>&lt;T&gt; {
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Item</span></span> = &amp;<span class="hljs-symbol">'a</span> <span class="hljs-keyword">mut</span> T;
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">IntoIter</span></span> = std::slice::IterMut&lt;<span class="hljs-symbol">'a</span>, T&gt;;

    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">into_iter</span></span>(<span class="hljs-keyword">self</span>) -&gt; Self::IntoIter { <span class="hljs-comment">/* ... */</span> }
}
</code></pre>
<p><code>std::slice::Iter&lt;'a, T&gt;</code> , <code>std::slice::IterMut&lt;'a, T&gt;</code> and <code>std::vec::IntoIter&lt;T&gt;</code> are <strong>different iterator types</strong> you're seeing in Rust. Each one corresponds to a different <strong>way of iterating</strong> over a collection, based on ownership and mutability.</p>
<h2 id="heading-understanding-intoiter-and-ownership">Understanding into_iter() and Ownership</h2>
<p>The <code>into_iter()</code> method can handle different ownership patterns, making Rust's iteration system super flexible. Let's discuss how it works with values, references, and mutable references, and how <code>iter()</code> fits into this system.</p>
<p><strong>How into_iter() works with different ownership types</strong></p>
<p>The <code>into_iter()</code> method behaves differently depending on whether you call it on:</p>
<ol>
<li><p><strong>Value (T)</strong>: Consumes the collection, taking ownership</p>
</li>
<li><p><strong>Reference (&amp;T)</strong>: Borrows the collection immutably</p>
</li>
<li><p><strong>Mutable reference (&amp;mut T)</strong>: Borrows the collection mutably</p>
</li>
</ol>
<p>This is achieved through separate implementations of the <code>IntoIterator</code> trait for each case.</p>
<pre><code class="lang-rust"><span class="hljs-comment">// For Vec&lt;T&gt; as an example:</span>
<span class="hljs-comment">// Takes ownership (consumes the Vec)</span>
<span class="hljs-keyword">impl</span>&lt;T&gt; <span class="hljs-built_in">IntoIterator</span> <span class="hljs-keyword">for</span> <span class="hljs-built_in">Vec</span>&lt;T&gt; {
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Item</span></span> = T;  <span class="hljs-comment">// Iterator yields owned values</span>
    <span class="hljs-comment">// ...</span>
}
<span class="hljs-comment">// Borrows immutably</span>
<span class="hljs-keyword">impl</span>&lt;<span class="hljs-symbol">'a</span>, T&gt; <span class="hljs-built_in">IntoIterator</span> <span class="hljs-keyword">for</span> &amp;<span class="hljs-symbol">'a</span> <span class="hljs-built_in">Vec</span>&lt;T&gt; {
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Item</span></span> = &amp;<span class="hljs-symbol">'a</span> T;  <span class="hljs-comment">// Iterator yields references</span>
    <span class="hljs-comment">// ...</span>
}
<span class="hljs-comment">// Borrows mutably</span>
<span class="hljs-keyword">impl</span>&lt;<span class="hljs-symbol">'a</span>, T&gt; <span class="hljs-built_in">IntoIterator</span> <span class="hljs-keyword">for</span> &amp;<span class="hljs-symbol">'a</span> <span class="hljs-keyword">mut</span> <span class="hljs-built_in">Vec</span>&lt;T&gt; {
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Item</span></span> = &amp;<span class="hljs-symbol">'a</span> <span class="hljs-keyword">mut</span> T;  <span class="hljs-comment">// Iterator yields mutable references</span>
    <span class="hljs-comment">// ...</span>
}
</code></pre>
<p><strong>Examples:</strong></p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> v = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];

<span class="hljs-comment">// Takes ownership - consumes v</span>
<span class="hljs-keyword">let</span> iter1 = v.into_iter();  <span class="hljs-comment">// Iterator yields values (T)</span>
<span class="hljs-comment">// v is no longer usable here</span>

<span class="hljs-keyword">let</span> v = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];

<span class="hljs-comment">// Borrows immutably</span>
<span class="hljs-keyword">let</span> iter2 = (&amp;v).into_iter();  <span class="hljs-comment">// Iterator yields references (&amp;T)</span>
<span class="hljs-comment">// v is still usable here</span>

<span class="hljs-comment">// Borrows mutably</span>
<span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> v = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">let</span> iter3 = (&amp;<span class="hljs-keyword">mut</span> v).into_iter();  <span class="hljs-comment">// Iterator yields mutable references (&amp;mut T)</span>
<span class="hljs-comment">// v is still usable after iter3 is dropped</span>

<span class="hljs-comment">// Standard collection methods</span>
<span class="hljs-keyword">let</span> v = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">let</span> iter_a = v.iter();          <span class="hljs-comment">// Always yields &amp;T</span>
<span class="hljs-keyword">let</span> iter_b = v.iter_mut();      <span class="hljs-comment">// Always yields &amp;mut T</span>
<span class="hljs-keyword">let</span> iter_c = v.into_iter();     <span class="hljs-comment">// Consumes v, yields T</span>
</code></pre>
<p>The flexibility of <code>into_iter()</code> is why <code>for</code> loops in Rust work with all three ownership models. The compiler automatically chooses the appropriate implementation based on how you use the collection in the loop.</p>
<h1 id="heading-iterator-trait">Iterator Trait</h1>
<p>The <code>Iterator</code> trait provides a way to process sequences of items one at a time, and it serves as the foundation for many functional programming patterns. <code>Iterator</code> and <code>IntoIterator</code> are two related but different traits that help in working with collections and iterators.</p>
<p><code>Iterator</code> is used when you <strong>already have</strong> an iterator and want to iterate over it. The <code>next()</code> method is used to fetch elements one by one.</p>
<p>Example:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> numbers = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> iter = numbers.iter(); <span class="hljs-comment">// Create an iterator over `numbers`</span>

<span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, iter.next()); <span class="hljs-comment">// Some(1)</span>
<span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, iter.next()); <span class="hljs-comment">// Some(2)</span>
<span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, iter.next()); <span class="hljs-comment">// Some(3)</span>
<span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, iter.next()); <span class="hljs-comment">// None (end of iteration)</span>
</code></pre>
<p><code>numbers.iter()</code> creates an iterator and calling <code>next()</code> moves through the elements.</p>
<h2 id="heading-basic-structure">Basic Structure</h2>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Iterator</span></span> {
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Item</span></span>;

    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">next</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">Option</span>&lt;Self::Item&gt;;
    <span class="hljs-comment">// Many default methods omitted...</span>
}
</code></pre>
<p>The trait has only one required method to implement: <code>next()</code>. Everything else is built on top of this foundation.</p>
<h2 id="heading-core-components">Core Components</h2>
<ol>
<li><p><strong>Associated Type</strong> <code>Item</code>: Defines what type of elements the iterator will produce.</p>
</li>
<li><p><code>next()</code> Method: The heart of the iterator pattern.</p>
<ul>
<li><p>Returns <code>Some(item)</code> if there's another item in the sequence</p>
</li>
<li><p>Returns <code>None</code> when iteration is complete</p>
</li>
<li><p>Takes <code>&amp;mut self</code> because advancing the iterator changes its internal state</p>
</li>
</ul>
</li>
</ol>
<h2 id="heading-implementing-iterator">Implementing Iterator</h2>
<p>Here's a simple example of implementing the <code>Iterator</code> trait:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Fibonacci</span></span> {
    curr: <span class="hljs-built_in">u32</span>,
    next: <span class="hljs-built_in">u32</span>,
}

<span class="hljs-keyword">impl</span> <span class="hljs-built_in">Iterator</span> <span class="hljs-keyword">for</span> Fibonacci {
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Item</span></span> = <span class="hljs-built_in">u32</span>;

    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">next</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">Option</span>&lt;Self::Item&gt; {
        <span class="hljs-keyword">let</span> current = <span class="hljs-keyword">self</span>.curr;
        <span class="hljs-keyword">self</span>.curr = <span class="hljs-keyword">self</span>.next;
        <span class="hljs-keyword">self</span>.next = current + <span class="hljs-keyword">self</span>.next;
        <span class="hljs-literal">Some</span>(current)
    }
}

<span class="hljs-comment">// Create an iterator that generates the Fibonacci sequence</span>
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">fibonacci</span></span>() -&gt; Fibonacci {
    Fibonacci { curr: <span class="hljs-number">0</span>, next: <span class="hljs-number">1</span> }
}

<span class="hljs-keyword">let</span> fib = fibonacci();
<span class="hljs-keyword">let</span> first_10: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u32</span>&gt; = fib.take(<span class="hljs-number">10</span>).collect();
</code></pre>
<h2 id="heading-relationship-to-intoiterator">Relationship to IntoIterator</h2>
<p><code>Iterator</code> defines how to iterate through a sequence. <code>IntoIterator</code> defines how to create an iterator from a value. These two work hand in hand to make a full iteration system. The <code>IntoIterator::into_iter()</code> method creates an <code>Iterator</code>, and when you use a <code>for</code> loop, it automatically uses <code>IntoIterator</code> behind the scenes.</p>
<p>This design allows for flexibility and powerful abstractions across Rust's standard library and ecosystem. The combination of these traits enables many of Rust's most elegant patterns for working with collections and sequences.</p>
<h3 id="heading-the-iter-method-vs-intoiter">The iter() Method vs. into_iter()</h3>
<p>The <code>iter()</code> method is <strong>not</strong> syntactic sugar for <code>&amp;collection.into_iter()</code>, but they're closely related.</p>
<p><code>iter()</code> is a method implemented specifically for collections in the standard library, while <code>into_iter()</code> comes from the <code>IntoIterator</code> trait. They serve similar purposes but work differently:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> v = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];

<span class="hljs-comment">// These two are equivalent:</span>
<span class="hljs-keyword">let</span> iter1 = v.iter();
<span class="hljs-keyword">let</span> iter2 = (&amp;v).into_iter();
<span class="hljs-comment">// Both produce iterators over &amp;T (references)</span>
</code></pre>
<h3 id="heading-important-distinctions"><strong>Important Distinctions:</strong></h3>
<ul>
<li><p><code>iter()</code> is a method found directly on collection types like Vec and HashMap, while <code>into_iter()</code> comes from the <code>IntoIterator</code> trait.</p>
</li>
<li><p><code>iter()</code> always borrows the collection and never consumes it, whereas <code>into_iter()</code> might consume the collection, depending on whether it's called on a value or a reference.</p>
</li>
<li><p><code>iter()</code> always gives you an iterator over references, while <code>into_iter()</code> behaves differently based on how you use it. And <code>iter_mut()</code> always provides an iterator over mutable references.</p>
</li>
</ul>
<h1 id="heading-full-example">Full Example</h1>
<p>Below is a detailed example of a custom <code>Portfolio</code> struct, which contains a <code>Vec&lt;String&gt;</code>. This example includes <strong>three</strong> distinct implementations of the <code>IntoIterator</code> trait, each designed to allow different types of iteration over the <code>Portfolio</code>:</p>
<ol>
<li><p><strong>Consuming iteration</strong>: This type of iteration occurs by value, meaning it takes ownership of the elements. It yields owned <code>String</code> values, effectively consuming the <code>Portfolio</code> as it iterates through its elements. This is useful when you need to take ownership of the data for further processing or transformation.</p>
</li>
<li><p><strong>Shared iteration</strong>: This iteration happens by shared reference, which means it does not take ownership of the elements. Instead, it yields <code>&amp;String</code>, allowing you to read the data without modifying it. This is ideal for scenarios where you need to access the data without altering the original <code>Portfolio</code>.</p>
</li>
<li><p><strong>Mutable iteration</strong>: This iteration is performed by mutable reference, yielding <code>&amp;mut String</code>. It lets you change the elements of the <code>Portfolio</code> as you go through them. This is especially useful when you need to update or transform the data right where it is.</p>
</li>
</ol>
<p>For each of these iteration types, we'll show how they work with a custom iterator type: <code>PortfolioIntoIter</code>, <code>PortfolioIter</code>, and <code>PortfolioIterMut</code>. Each of these custom iterator types implements the <code>Iterator</code> trait, giving you the tools you need to go through the <code>Portfolio</code> in the way you want. This setup not only highlights the flexibility of Rust's iteration patterns but also shows how you can create custom iterators to fit your specific needs.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Portfolio</span></span> {
    instruments: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">String</span>&gt;,
}

<span class="hljs-comment">// An iterator for consuming `Portfolio` (yields owned `String`)</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">PortfolioIntoIter</span></span> {
    inner: std::vec::IntoIter&lt;<span class="hljs-built_in">String</span>&gt;,
}

<span class="hljs-comment">// An iterator for `&amp;Portfolio` (yields `&amp;String`)</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">PortfolioIter</span></span>&lt;<span class="hljs-symbol">'a</span>&gt; {
    inner: std::slice::Iter&lt;<span class="hljs-symbol">'a</span>, <span class="hljs-built_in">String</span>&gt;,
}

<span class="hljs-comment">// An iterator for `&amp;mut Portfolio` (yields `&amp;mut String`)</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">PortfolioIterMut</span></span>&lt;<span class="hljs-symbol">'a</span>&gt; {
    inner: std::slice::IterMut&lt;<span class="hljs-symbol">'a</span>, <span class="hljs-built_in">String</span>&gt;,
}

<span class="hljs-comment">// Constructor for convenience</span>
<span class="hljs-keyword">impl</span> Portfolio {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>(instruments: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">String</span>&gt;) -&gt; <span class="hljs-keyword">Self</span> {
        Portfolio { instruments }
    }
}
</code></pre>
<p>Now, let's delve into implementing the three distinct variants of the <code>IntoIterator</code> trait for our custom iterator types.</p>
<pre><code class="lang-rust"><span class="hljs-comment">// 1) By value (Portfolio -&gt; owned iteration)</span>
<span class="hljs-keyword">impl</span> <span class="hljs-built_in">IntoIterator</span> <span class="hljs-keyword">for</span> Portfolio {
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Item</span></span> = <span class="hljs-built_in">String</span>;
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">IntoIter</span></span> = PortfolioIntoIter;

    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">into_iter</span></span>(<span class="hljs-keyword">self</span>) -&gt; Self::IntoIter {
        PortfolioIntoIter {
            <span class="hljs-comment">// Move out the vector’s own iterator</span>
            inner: <span class="hljs-keyword">self</span>.instruments.into_iter(),
        }
    }
}

<span class="hljs-comment">// 2) By shared reference (&amp;Portfolio -&gt; shared iteration)</span>
<span class="hljs-keyword">impl</span>&lt;<span class="hljs-symbol">'a</span>&gt; <span class="hljs-built_in">IntoIterator</span> <span class="hljs-keyword">for</span> &amp;<span class="hljs-symbol">'a</span> Portfolio {
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Item</span></span> = &amp;<span class="hljs-symbol">'a</span> <span class="hljs-built_in">String</span>;
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">IntoIter</span></span> = PortfolioIter&lt;<span class="hljs-symbol">'a</span>&gt;;

    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">into_iter</span></span>(<span class="hljs-keyword">self</span>) -&gt; Self::IntoIter {
        PortfolioIter {
            <span class="hljs-comment">// Borrow the underlying vector’s iterator</span>
            inner: <span class="hljs-keyword">self</span>.instruments.iter(),
        }
    }
}

<span class="hljs-comment">// 3) By mutable reference (&amp;mut Portfolio -&gt; mutable iteration)</span>
<span class="hljs-keyword">impl</span>&lt;<span class="hljs-symbol">'a</span>&gt; <span class="hljs-built_in">IntoIterator</span> <span class="hljs-keyword">for</span> &amp;<span class="hljs-symbol">'a</span> <span class="hljs-keyword">mut</span> Portfolio {
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Item</span></span> = &amp;<span class="hljs-symbol">'a</span> <span class="hljs-keyword">mut</span> <span class="hljs-built_in">String</span>;
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">IntoIter</span></span> = PortfolioIterMut&lt;<span class="hljs-symbol">'a</span>&gt;;

    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">into_iter</span></span>(<span class="hljs-keyword">self</span>) -&gt; Self::IntoIter {
        PortfolioIterMut {
            <span class="hljs-comment">// Borrow the underlying vector’s mutable iterator</span>
            inner: <span class="hljs-keyword">self</span>.instruments.iter_mut(),
        }
    }
}
</code></pre>
<p>Now, let's proceed to implement the <code>Iterator</code> trait for each of our custom iterator types. This step is crucial because it defines how each iterator will behave when traversing through the elements of the <code>Portfolio</code>. By implementing the <code>Iterator</code> trait, we specifically implement <code>next()</code> for different iterators to advance the iterator and yield the value.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span> <span class="hljs-built_in">Iterator</span> <span class="hljs-keyword">for</span> PortfolioIntoIter {
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Item</span></span> = <span class="hljs-built_in">String</span>;

    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">next</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">Option</span>&lt;Self::Item&gt; {
        <span class="hljs-keyword">self</span>.inner.next()
    }
}

<span class="hljs-keyword">impl</span>&lt;<span class="hljs-symbol">'a</span>&gt; <span class="hljs-built_in">Iterator</span> <span class="hljs-keyword">for</span> PortfolioIter&lt;<span class="hljs-symbol">'a</span>&gt; {
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Item</span></span> = &amp;<span class="hljs-symbol">'a</span> <span class="hljs-built_in">String</span>;

    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">next</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">Option</span>&lt;Self::Item&gt; {
        <span class="hljs-keyword">self</span>.inner.next()
    }
}

<span class="hljs-keyword">impl</span>&lt;<span class="hljs-symbol">'a</span>&gt; <span class="hljs-built_in">Iterator</span> <span class="hljs-keyword">for</span> PortfolioIterMut&lt;<span class="hljs-symbol">'a</span>&gt; {
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Item</span></span> = &amp;<span class="hljs-symbol">'a</span> <span class="hljs-keyword">mut</span> <span class="hljs-built_in">String</span>;

    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">next</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">Option</span>&lt;Self::Item&gt; {
        <span class="hljs-keyword">self</span>.inner.next()
    }
}
</code></pre>
<p>Example usage in main() where we create a <code>Portfolio</code> instance and iterate over its elements using the different iterator implementations we have defined above.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-comment">// 1) By value: move the Portfolio and get owned Strings</span>
    <span class="hljs-keyword">let</span> portfolio = Portfolio::new(<span class="hljs-built_in">vec!</span>[<span class="hljs-string">"AAPL"</span>.into(), <span class="hljs-string">"GOOG"</span>.into(), <span class="hljs-string">"MSFT"</span>.into()]);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Iterate by value:"</span>);
    <span class="hljs-keyword">for</span> instrument <span class="hljs-keyword">in</span> portfolio.into_iter() {
        <span class="hljs-comment">// instrument is String (owned)</span>
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, instrument);
    }
    <span class="hljs-comment">// `portfolio` is consumed here—can't use it again.</span>

    <span class="hljs-comment">// 2) By shared reference: get &amp;String</span>
    <span class="hljs-keyword">let</span> portfolio_ref = Portfolio::new(<span class="hljs-built_in">vec!</span>[<span class="hljs-string">"TSLA"</span>.into(), <span class="hljs-string">"AMZN"</span>.into(), <span class="hljs-string">"META"</span>.into()]);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"\nIterate by shared reference:"</span>);
    <span class="hljs-keyword">for</span> instrument <span class="hljs-keyword">in</span> &amp;portfolio_ref {
        <span class="hljs-comment">// instrument is &amp;String</span>
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, instrument);
    }
    <span class="hljs-comment">// `portfolio_ref` is still usable (not consumed).</span>

    <span class="hljs-comment">// 3) By mutable reference: get &amp;mut String</span>
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> portfolio_mut = Portfolio::new(<span class="hljs-built_in">vec!</span>[<span class="hljs-string">"NFLX"</span>.into(), <span class="hljs-string">"DIS"</span>.into()]);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"\nIterate by mutable reference:"</span>);
    <span class="hljs-keyword">for</span> instrument <span class="hljs-keyword">in</span> &amp;<span class="hljs-keyword">mut</span> portfolio_mut {
        <span class="hljs-comment">// instrument is &amp;mut String</span>
        instrument.push_str(<span class="hljs-string">" (edited)"</span>);
    }
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, portfolio_mut);
}
</code></pre>
<p><strong>Output</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1742691832840/6a2867fe-6932-45dc-aed0-83d83207bd15.png" alt class="image--center mx-auto" /></p>
<p>With this setup, the same <code>.into_iter()</code> method name can produce <strong>three different iterator types</strong> depending on the context of how you call it (owned, immutable reference, or mutable reference)—exactly like <code>Vec&lt;T&gt;</code> does in the standard library.</p>
<h1 id="heading-iterators-without-boilerplate-successors">Iterators Without Boilerplate: successors</h1>
<p>Instead of writing a custom iterator, you can define your sequence generation logic inline with just a closure using successors. <code>successors</code> is a <strong>function</strong> in the Rust standard library (<code>std::iter</code>) that creates an <strong>iterator</strong> from an initial value and a “successor function.” Formally:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">successors</span></span>&lt;T, F&gt;(first: <span class="hljs-built_in">Option</span>&lt;T&gt;, succ: F) -&gt; Successors&lt;T, F&gt;
<span class="hljs-keyword">where</span>
    F: <span class="hljs-built_in">FnMut</span>(&amp;T) -&gt; <span class="hljs-built_in">Option</span>&lt;T&gt;,
</code></pre>
<p><code>first</code> is an <code>Option&lt;T&gt;</code> – your <strong>starting point</strong> (may or may not exist) and <code>succ</code> is a closure or function that, given a reference to the <strong>most recently yielded value</strong>, returns the <strong>next</strong> value as an <code>Option&lt;T&gt;</code>.</p>
<p>The iterator produced will:</p>
<ul>
<li><p>Yield the <code>first</code> value <strong>if</strong> it’s <code>Some(...)</code>.</p>
</li>
<li><p>Then repeatedly call <code>succ</code> on the last yielded value to get the next.</p>
</li>
<li><p>Stop once <code>succ</code> returns <code>None</code>.</p>
</li>
</ul>
<p>This means you can <strong>generate a sequence</strong> on-the-fly <strong>without</strong> building your own <code>struct</code> and implementing <code>Iterator</code> manually.</p>
<p>If you like chaining and pipelining, <code>successors</code> fits right in. You can follow it with methods like <code>.map(...)</code>, <code>.filter(...)</code>, etc., and then <code>.take(...)</code> or <code>.collect()</code> as needed.</p>
<p>Here’s a simple example that starts from <code>Some(1)</code> and then keeps adding 1 until we decide to stop at a certain condition.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::iter::successors;
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> iter = successors(<span class="hljs-literal">Some</span>(<span class="hljs-number">1</span>), |&amp;prev| {
        <span class="hljs-keyword">let</span> next = prev + <span class="hljs-number">1</span>;
        <span class="hljs-keyword">if</span> next &lt;= <span class="hljs-number">5</span> {
            <span class="hljs-literal">Some</span>(next)
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-literal">None</span>
        }
    });

    <span class="hljs-comment">// Collect into a vector</span>
    <span class="hljs-keyword">let</span> values: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt; = iter.collect();
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, values); <span class="hljs-comment">// [1, 2, 3, 4, 5]</span>
}
</code></pre>
<p>We pass <code>Some(1)</code> as the first value, so <code>1</code> is yielded immediately when iteration begins. For each subsequent item, we apply the closure <code>|&amp;prev| { ... }</code>. The iterator yields <code>1, 2, 3, 4, 5</code>, then stops.</p>
<p>We can implement our previous example <strong>Fibonacci sequence</strong> using <code>std::iter::successors</code> as well.</p>
<p>Here’s the equivalent version of <code>Fibonacci</code> iterator using <code>successor</code>.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::iter;
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">fibonacci</span></span>() -&gt; <span class="hljs-keyword">impl</span> <span class="hljs-built_in">Iterator</span>&lt;Item = <span class="hljs-built_in">u32</span>&gt; {
    iter::successors(<span class="hljs-literal">Some</span>((<span class="hljs-number">0</span>, <span class="hljs-number">1</span>)), |&amp;(curr, next)| {
        <span class="hljs-literal">Some</span>((next, curr + next))
    })
    .map(|(curr, _)| curr)
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> first_10: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">u32</span>&gt; = fibonacci().take(<span class="hljs-number">10</span>).collect();
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, first_10); <span class="hljs-comment">// [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]</span>
}
</code></pre>
<p><strong>Overall Easier Setup</strong>: <code>successors(Some(start), |&amp;prev| Some(next))</code> is all you need to define a sequence and it is more functional-style code.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Iterators are a fundamental concept in programming that provide a powerful and flexible way to traverse and manipulate collections. By abstracting the underlying data structure, iterators offer a safe and efficient means to perform operations like mapping, filtering, and reducing. In Rust, the iterator system is particularly robust, supporting lazy evaluation, ownership, borrowing, and a wide range of combinators that enhance code readability and maintainability. Understanding the different traits and methods associated with iterators, such as <code>Iterator</code> and <code>IntoIterator</code>, allows you to write more expressive and efficient code.</p>
]]></content:encoded></item><item><title><![CDATA[Closure: Lambda Functions of Rust]]></title><description><![CDATA[A closure is an anonymous function that can capture variables from its environment. At a high level, Rust closures allow you to write small, concise functions inline, without having to formally define a new fn with a name. They’re particularly handy ...]]></description><link>https://siddharthqs.com/closure-lambda-functions-of-rust</link><guid isPermaLink="true">https://siddharthqs.com/closure-lambda-functions-of-rust</guid><category><![CDATA[Rust]]></category><category><![CDATA[Lambda function]]></category><category><![CDATA[Closures]]></category><category><![CDATA[Functional Programming]]></category><dc:creator><![CDATA[Siddharth]]></dc:creator><pubDate>Fri, 07 Mar 2025 06:20:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/VLaKsTkmVhk/upload/0591e76d111257592e82dfc570d6e306.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A <strong>closure</strong> is an anonymous function that can capture variables from its environment. At a high level, Rust closures allow you to write small, concise functions inline, without having to formally define a new <code>fn</code> with a name. They’re particularly handy when you want to pass a piece of functionality around, such as to iterators or threads.</p>
<p>Capturing <strong>variables from its enclosing scope</strong> means you don’t have to manually pass those variables as parameters; the compiler implicitly makes them accessible inside the closure.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> x = <span class="hljs-number">10</span>;
<span class="hljs-comment">// `double_x` is a closure that captures `x` from the environment</span>
<span class="hljs-keyword">let</span> double_x = || x * <span class="hljs-number">2</span>;
</code></pre>
<h2 id="heading-closure-syntax">Closure Syntax</h2>
<p>Parameters in pipes (<code>|</code>)</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> closure = |param1, param2| {
    <span class="hljs-comment">// body</span>
};
</code></pre>
<p><strong>Optional curly braces</strong> if the body is a single expression:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> closure = |x| x + <span class="hljs-number">1</span>;
</code></pre>
<p>Often, you don't have to specify types for the parameters, but if you'd like to be clear, you certainly can.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> add = |a, b| a + b;
<span class="hljs-keyword">let</span> add = |a: <span class="hljs-built_in">i32</span>, b: <span class="hljs-built_in">i32</span>| -&gt; <span class="hljs-built_in">i32</span> { a + b };
</code></pre>
<h2 id="heading-capturing-variables">Capturing Variables</h2>
<p>Unlike standard functions, closures have a special talent for capturing variables from the scope where they are created. Rust closures can capture:</p>
<ol>
<li><p><strong>By reference</strong> (<code>&amp;T</code>)</p>
</li>
<li><p><strong>By mutable reference</strong> (<code>&amp;mut T</code>)</p>
</li>
<li><p><strong>By value / move</strong> (<code>T</code>)</p>
</li>
</ol>
<h3 id="heading-how-rust-decides-the-capture-method">How Rust Decides the Capture Method</h3>
<p>Rust uses <strong>capture inference</strong> to figure out the best way to capture each variable. It decides this based on how the closure <em>uses</em> the variable:</p>
<ol>
<li><p><strong>If the closure just needs to read the variable</strong>, it will capture it by <strong>immutable reference</strong>.</p>
</li>
<li><p><strong>If the closure needs to change the variable</strong>, it will capture it by <strong>mutable reference</strong>.</p>
</li>
<li><p><strong>If the closure needs to take full ownership of the variable</strong> (like when it moves it or keeps it somewhere that lasts longer than the current scope), it will capture it by <strong>value</strong> (ownership).</p>
</li>
</ol>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello"</span>);
    <span class="hljs-keyword">let</span> print_s = || <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, s); <span class="hljs-comment">// 1) Capture by reference</span>

    print_s(); <span class="hljs-comment">// Prints "hello"</span>
    <span class="hljs-comment">// This closure modifies `s`, so it captures `s` by &amp;mut.</span>
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> append_exclamation = || {    <span class="hljs-comment">// 2) Capture by mutable reference</span>
        s.push(<span class="hljs-string">'!'</span>);
    };

    append_exclamation();
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, s); <span class="hljs-comment">// "hello!"</span>

    <span class="hljs-comment">// 3) Capture by value (move) Using move explicitly forces ownership capture.</span>
    <span class="hljs-keyword">let</span> take_ownership = <span class="hljs-keyword">move</span> || {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Moved: {}"</span>, s);
    }; 
    take_ownership();
}
</code></pre>
<p>Lets try to print s after running take_ownerhship closure</p>
<pre><code class="lang-rust"><span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, s); 

error[E0382]: borrow of moved value: `s`
  --&gt; src/main.rs:<span class="hljs-number">20</span>:<span class="hljs-number">20</span>
   |
<span class="hljs-number">2</span>  |     <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"hello"</span>);
   |         ----- <span class="hljs-keyword">move</span> occurs because `s` has <span class="hljs-class"><span class="hljs-keyword">type</span> `<span class="hljs-title">String</span></span>`, which does not implement the `<span class="hljs-built_in">Copy</span>` <span class="hljs-class"><span class="hljs-keyword">trait</span>
...
15 |     <span class="hljs-title">let</span></span> take_ownership = <span class="hljs-keyword">move</span> || {
   |                          ------- value moved into closure here
<span class="hljs-number">16</span> |         <span class="hljs-comment">// We won't be able to use `s` after this closure is created if it truly takes it by value.</span>
<span class="hljs-number">17</span> |         <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Moved: {}"</span>, s);
   |                               - variable moved due to <span class="hljs-keyword">use</span> <span class="hljs-keyword">in</span> closure
...
<span class="hljs-number">20</span> |     <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, s); <span class="hljs-comment">// Error: `s` was moved</span>
   |                    ^ value borrowed here after <span class="hljs-keyword">move</span>
</code></pre>
<h2 id="heading-the-move-keyword">The <code>move</code> Keyword</h2>
<p>By default, the compiler uses the least restrictive capture mode it can. But if you want to change that, you can use <code>move</code>. This makes sure <strong>all</strong> captures in that closure take ownership, using move semantics.</p>
<h2 id="heading-closure-traits-fn-fnmut-and-fnonce">Closure Traits: <code>Fn</code>, <code>FnMut</code>, and <code>FnOnce</code></h2>
<p>Closures can implement one or more of these <strong>function traits</strong>, based on how they capture their environment:</p>
<p><code>Fn</code>: A closure that only needs an <strong>immutable reference</strong> to its environment.</p>
<p><code>FnMut</code>: A closure that only needs a <strong>mutable reference</strong> to its environment.</p>
<p><code>FnOnce</code>: A closure that can be called <strong>at least once</strong>. It may consume (move) variables it captures, so it can only be called once if it moves.</p>
<p>Conceptually, you can think of them as:</p>
<ul>
<li><p><code>FnOnce</code>: uses <code>self</code></p>
</li>
<li><p><code>FnMut</code>: uses <code>&amp;mut self</code></p>
</li>
<li><p><code>Fn</code>: uses <code>&amp;self</code></p>
</li>
</ul>
<p>Let do a bit of deep dive on these traits.</p>
<h2 id="heading-fn-trait"><code>Fn</code> trait</h2>
<p>As described in Rust documentation, <code>Fn</code> is the trait for <em>function-like</em> types that can be <strong>called repeatedly</strong> without needing to change anything in their environment. Put simply, if a piece of code can be <strong>called multiple times</strong> and doesn’t need to <strong>mutate</strong> (change) any variables it has captured, it usually implements <code>Fn</code>. <em>This trait (</em><code>Fn</code>) should not be confused with <a target="_blank" href="https://doc.rust-lang.org/std/primitive.fn.html">function pointers</a> (<code>fn</code>).</p>
<h3 id="heading-fn-vs-fn-function-pointers"><code>Fn</code> vs. <code>fn</code> (Function Pointers)</h3>
<ul>
<li><p><code>fn</code> (lowercase) refers to a <strong>function pointer</strong> type. For example, <code>fn(i32) -&gt; i32</code> is a pointer to a function that takes an <code>i32</code> and returns an <code>i32</code>.</p>
</li>
<li><p><code>Fn</code> (uppercase) is a <strong>trait</strong>, which can be implemented by <em>any</em> callable type, such as:</p>
<ul>
<li><p><strong>Closures</strong> (anonymous functions that capture variables),</p>
</li>
<li><p><strong>Function pointers</strong> (<code>fn(...)</code>) themselves,</p>
</li>
<li><p>or even your own custom types that implement the <code>Fn</code> trait.</p>
</li>
</ul>
</li>
</ul>
<p>To illustrate, consider a function that takes an integer as input and returns its square. In Rust, a <strong>function pointer</strong> has the type <code>fn(…) -&gt; …</code>. For example, here is a simple function that squares an integer:</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">square</span></span>(x: <span class="hljs-built_in">i32</span>) -&gt; <span class="hljs-built_in">i32</span> {
    x * x
}
</code></pre>
<p>We can create a function that <strong>accepts</strong> a function pointer of this type. <code>apply_square</code> takes a parameter <code>f: fn(i32) -&gt; i32</code>. This means the caller needs to pass a <strong>pointer to a function</strong> with that exact signature (no captures, no closures). We can pass <code>square</code> (a regular function) to it, and it works perfectly.</p>
<pre><code class="lang-rust"><span class="hljs-comment">// Accepts a function pointer "fn(i32) -&gt; i32".</span>
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">apply_square</span></span>(f: <span class="hljs-function"><span class="hljs-keyword">fn</span></span>(<span class="hljs-built_in">i32</span>) -&gt; <span class="hljs-built_in">i32</span>, value: <span class="hljs-built_in">i32</span>) -&gt; <span class="hljs-built_in">i32</span> {
    f(value)
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> result = apply_square(square, <span class="hljs-number">4</span>);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Result using function pointer: {}"</span>, result); 
}
</code></pre>
<p>If we try to pass a <strong>closure</strong> instead of a function pointer, you may expect a compilation error or warning.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> closure = |x: <span class="hljs-built_in">i32</span>| x * x;
<span class="hljs-keyword">let</span> result = apply_square(closure, <span class="hljs-number">4</span>);
</code></pre>
<p>Wait, it worked perfectly as well and we know <strong>Closures</strong> in Rust are <strong>not</strong> the same type as <code>fn(…) -&gt; …</code>.</p>
<p>In this case, a <strong>closure</strong> <strong>does not capture anything</strong> from its environment (i.e., it doesn’t use any local variables from the enclosing scope) is effectively equivalent to a plain function. Rust can <strong>coerce</strong> (convert) that closure into a <strong>function pointer</strong>. This is a <strong>special-case automatic conversion</strong> allowed by the compiler.</p>
<p>Lets capture some variable from its environment.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> x = <span class="hljs-number">4</span>;
<span class="hljs-keyword">let</span> closure = || x * x;
<span class="hljs-keyword">let</span> result = apply_square(closure, x);

error[E0308]: mismatched types
  --&gt; src/main.rs:<span class="hljs-number">24</span>:<span class="hljs-number">40</span>
   |
<span class="hljs-number">22</span> |     <span class="hljs-keyword">let</span> closure = || x * x;
   |                   -- the found closure
<span class="hljs-number">23</span> |     
<span class="hljs-number">24</span> |     <span class="hljs-keyword">let</span> result = apply_square(closure, x);
   |                  --------------------- ^^^^^^^ expected <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">pointer</span>, <span class="hljs-title">found</span> <span class="hljs-title">closure</span>
   |                  |
   |                  <span class="hljs-title">arguments</span> <span class="hljs-title">to</span> <span class="hljs-title">this</span> <span class="hljs-title">function</span> <span class="hljs-title">are</span> <span class="hljs-title">incorrect</span>
   |
   = <span class="hljs-title">note</span>: <span class="hljs-title">expected</span> <span class="hljs-title">fn</span> <span class="hljs-title">pointer</span> `<span class="hljs-title">fn</span></span>(<span class="hljs-built_in">i32</span>) -&gt; <span class="hljs-built_in">i32</span>`
                 found closure `{closure@src/main.rs:<span class="hljs-number">22</span>:<span class="hljs-number">19</span>: <span class="hljs-number">22</span>:<span class="hljs-number">21</span>}`
note: closures can only be coerced to `<span class="hljs-function"><span class="hljs-keyword">fn</span>` <span class="hljs-title">types</span> <span class="hljs-title">if</span> <span class="hljs-title">they</span> <span class="hljs-title">do</span> <span class="hljs-title">not</span> <span class="hljs-title">capture</span> <span class="hljs-title">any</span> <span class="hljs-title">variables</span>
  --&gt; <span class="hljs-title">src</span>/<span class="hljs-title">main</span>.<span class="hljs-title">rs</span>:22:22
   |
22 |     <span class="hljs-title">let</span> <span class="hljs-title">closure</span> = || <span class="hljs-title">x</span> * <span class="hljs-title">x</span>;
   |                      ^ `<span class="hljs-title">x</span>` <span class="hljs-title">captured</span> <span class="hljs-title">here</span>
<span class="hljs-title">note</span>: <span class="hljs-title">function</span> <span class="hljs-title">defined</span> <span class="hljs-title">here</span>
  --&gt; <span class="hljs-title">src</span>/<span class="hljs-title">main</span>.<span class="hljs-title">rs</span>:7:4</span>
</code></pre>
<p>To allow a capturing closure to pass, you need to use a <strong>trait bound</strong> like Fn</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">apply_square_fn</span></span>&lt;F&gt;(f: F) -&gt; <span class="hljs-built_in">i32</span>
<span class="hljs-keyword">where</span>
    F: <span class="hljs-built_in">Fn</span>() -&gt; <span class="hljs-built_in">i32</span>,
{
    f()
}
<span class="hljs-keyword">let</span> x = <span class="hljs-number">4</span>;
<span class="hljs-keyword">let</span> closure = || x * x;
<span class="hljs-keyword">let</span> result = apply_square_fn(closure);
</code></pre>
<p>The main thing to remember is that <code>fn(i32) -&gt; i32</code> is a <em>function pointer type</em>. It's only for real functions or some non-capturing closures that can be turned into a <code>fn</code> pointer. If you set your parameter as a function pointer type, you <strong>can't</strong> pass a capturing closure. It <strong>does not</strong> capture any state.</p>
<h2 id="heading-fnmut-trait"><code>FnMut</code> Trait</h2>
<p>A closure that only needs a <strong>mutable reference</strong> to its environment. It can be called repeatedly, but it might mutate captured variables. <code>FnMut</code> is implemented automatically by closures which take mutable references to captured variables, as well as all types that implement <a target="_blank" href="https://doc.rust-lang.org/std/ops/trait.Fn.html"><code>Fn</code></a>. Any <code>FnMut</code> is automatically also an <code>FnOnce</code>, because if you can call something multiple times, you can at least call it once.</p>
<p>In the below example, the closure <strong>changes</strong> <code>count</code>. Therefore, it needs a <strong>mutable borrow</strong> of <code>count</code>. That means it implements at least <code>FnMut</code>.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> count = <span class="hljs-number">0</span>;
<span class="hljs-comment">// This closure captures `count` by mutable reference,</span>
<span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> increment = || { count += <span class="hljs-number">1</span>  }; <span class="hljs-comment">// compiler infers `increment: FnMut() -&gt; ()`.</span>

increment(); <span class="hljs-comment">//"count: 1"</span>
increment(); <span class="hljs-comment">//"count: 2"</span>
<span class="hljs-built_in">println!</span>(<span class="hljs-string">"Final count: {}"</span>, count); <span class="hljs-comment">// 2</span>
</code></pre>
<h3 id="heading-using-fnmut-as-a-trait-bound">Using <code>FnMut</code> as a Trait Bound</h3>
<p>Often, you’ll write <strong>generic functions</strong> that accept any closure (or function) with certain capabilities. If your function needs to <em>call a closure multiple times</em> and <em>allow it to mutate captured state</em>, you should use an <code>FnMut</code> bound.</p>
<pre><code class="lang-rust"><span class="hljs-comment">// It requires that `f` can be called multiple times AND can mutate state.</span>
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">call_multiple_times</span></span>&lt;F&gt;(<span class="hljs-keyword">mut</span> f: F, times: <span class="hljs-built_in">usize</span>)
<span class="hljs-keyword">where</span>
    F: <span class="hljs-built_in">FnMut</span>(),
{
    <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..times {
        f();
    }
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> counter = <span class="hljs-number">0</span>;

    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> increment = || {
        counter += <span class="hljs-number">1</span>;
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"counter: {}"</span>, counter);
    };
    <span class="hljs-comment">// The closure implements `FnMut`, so it's valid here.</span>
    call_multiple_times(increment, <span class="hljs-number">3</span>);
    <span class="hljs-comment">// Output:</span>
    <span class="hljs-comment">// counter: 1</span>
    <span class="hljs-comment">// counter: 2</span>
    <span class="hljs-comment">// counter: 3</span>

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Final counter: {}"</span>, counter); <span class="hljs-comment">// 3</span>
}
</code></pre>
<p><code>FnMut</code> is the trait for callables that may mutate captured state and can be called multiple times.</p>
<h2 id="heading-fnonce-trait"><code>FnOnce</code> Trait</h2>
<p>A closure that can be called <strong>at least once</strong>. It may consume (move) variables it captures, so it can only be called once if it moves something out of the environment. Every closure implements <code>FnOnce</code> because, at the bare minimum, you can call it once.</p>
<p>In simple terms, <strong>if a closure takes ownership of data from its environment, it's at least</strong> <code>FnOnce</code>. It could also be <code>FnMut</code> or <code>Fn</code>, based on whether it changes or just reads that data.</p>
<blockquote>
<p>Every closure implements at least one of these traits, and sometimes more, depending on how it handles variables.</p>
</blockquote>
<p>Essentially:</p>
<blockquote>
<p>FnOnce &lt;= FnMut &lt;= Fn</p>
</blockquote>
<p>(<code>FnOnce</code> is the “weakest” requirement; <code>Fn</code> is the “strongest”)</p>
<h2 id="heading-manually-implementing-fn">Manually Implementing <code>Fn</code></h2>
<p>In most real-world Rust code, you <strong>do not</strong> manually implement <code>Fn</code>, because <strong>closures and function pointers</strong> automatically implement it. However, if you want a custom <strong>struct</strong> to behave like a function, you need to implement <code>Fn</code>, <code>FnMut</code>, and <code>FnOnce</code> by hand.</p>
<p><strong>Important</strong>: This is only possible with <strong>nightly Rust</strong>, using special features. You can manually implement <code>Fn</code>, <code>FnMut</code>, or <code>FnOnce</code> by enabling <code>unboxed_closures</code> and <code>fn_traits</code>, using the <code>extern "rust-call"</code> syntax.</p>
<p>Below is a <strong>nightly-only</strong> example. It shows a <code>struct MultiplyBy</code> that holds a multiplier. We implement all three traits so that it can be called like a function.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#![feature(fn_traits)]</span>
<span class="hljs-meta">#![feature(unboxed_closures)]</span>
<span class="hljs-keyword">use</span> std::ops::{<span class="hljs-built_in">Fn</span>, <span class="hljs-built_in">FnMut</span>, <span class="hljs-built_in">FnOnce</span>};

<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">MultiplyBy</span></span>(<span class="hljs-built_in">i32</span>); <span class="hljs-comment">// A struct that holds a multiplier.</span>

<span class="hljs-comment">//1) Implement FnOnce for MultiplyBy. Notice the signature uses `call_once(self, (arg,): (i32,))`.</span>
<span class="hljs-keyword">impl</span> <span class="hljs-built_in">FnOnce</span>&lt;(<span class="hljs-built_in">i32</span>,)&gt; <span class="hljs-keyword">for</span> MultiplyBy {
    <span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Output</span></span> = <span class="hljs-built_in">i32</span>;

    <span class="hljs-keyword">extern</span> <span class="hljs-string">"rust-call"</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">call_once</span></span>(<span class="hljs-keyword">self</span>, (arg,): (<span class="hljs-built_in">i32</span>,)) -&gt; Self::Output {
        <span class="hljs-keyword">self</span>.<span class="hljs-number">0</span> * arg
    }
}
<span class="hljs-comment">//2)Implement FnMut for MultiplyBy. This time the method is `call_mut(&amp;mut self, (arg,): (i32,))`.</span>
<span class="hljs-keyword">impl</span> <span class="hljs-built_in">FnMut</span>&lt;(<span class="hljs-built_in">i32</span>,)&gt; <span class="hljs-keyword">for</span> MultiplyBy {
    <span class="hljs-keyword">extern</span> <span class="hljs-string">"rust-call"</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">call_mut</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, (arg,): (<span class="hljs-built_in">i32</span>,)) -&gt; Self::Output {
        <span class="hljs-keyword">self</span>.<span class="hljs-number">0</span> * arg
    }
}
<span class="hljs-comment">// 3) Finally, implement Fn for MultiplyB. Now we use `&amp;self`.</span>
<span class="hljs-keyword">impl</span> <span class="hljs-built_in">Fn</span>&lt;(<span class="hljs-built_in">i32</span>,)&gt; <span class="hljs-keyword">for</span> MultiplyBy {
    <span class="hljs-keyword">extern</span> <span class="hljs-string">"rust-call"</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">call</span></span>(&amp;<span class="hljs-keyword">self</span>, (arg,): (<span class="hljs-built_in">i32</span>,)) -&gt; Self::Output {
        <span class="hljs-keyword">self</span>.<span class="hljs-number">0</span> * arg
    }
}
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> multiply_by_10 = MultiplyBy(<span class="hljs-number">10</span>);
    <span class="hljs-comment">// Because we've implemented Fn, we can call our struct like a function:</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, multiply_by_10(<span class="hljs-number">5</span>));  <span class="hljs-comment">// 50</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, multiply_by_10(<span class="hljs-number">12</span>)); <span class="hljs-comment">// 120</span>
}
</code></pre>
<p><strong>Why implement all three?</strong><br />In Rust, <code>Fn</code> is a <em>supertrait</em> of <code>FnMut</code>, which is a <em>supertrait</em> of <code>FnOnce</code>. So you need to implement them in ascending order if you want a type to fully behave like a closure that can be called multiple times without mutation.</p>
<ul>
<li><p><code>FnOnce</code> says “I can be called <em>once</em>.”</p>
</li>
<li><p><code>FnMut</code> says “I can be called multiple times, mutably.”</p>
</li>
<li><p><code>Fn</code> says “I can be called multiple times, immutably.”</p>
</li>
</ul>
<h2 id="heading-under-the-hood-anonymous-struct-holding-captures">Under the hood: Anonymous Struct Holding Captures</h2>
<p>When you write a closure, Rust will <strong>create</strong> a hidden struct (let’s call it the <strong>closure object</strong>) that:</p>
<ol>
<li><p><strong>Has fields</strong> for each variable it captures.</p>
</li>
<li><p><strong>Implements</strong> one or more of the <code>FnOnce</code>, <code>FnMut</code>, and/or <code>Fn</code> traits.</p>
</li>
<li><p><strong>Implements</strong> a “call” method (i.e. <code>call</code>, <code>call_mut</code>, or <code>call_once</code>) that executes the closure body, referencing or consuming those fields as needed.</p>
</li>
</ol>
<p>Compiler generates this struct with name something like <code>closure@ID</code>.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> count = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> increment = || {
        count += <span class="hljs-number">1</span>;
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"count: {}"</span>, count);
    };

    increment();
    increment();
}
</code></pre>
<p>Conceptually, Rust might generate a struct like:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Closure_CountMut</span></span>&lt;<span class="hljs-symbol">'a</span>&gt; {
    count_ref: &amp;<span class="hljs-symbol">'a</span> <span class="hljs-keyword">mut</span> <span class="hljs-built_in">i32</span>,
}

<span class="hljs-comment">// This closure implements FnMut, because it mutates its captures.</span>
<span class="hljs-keyword">impl</span>&lt;<span class="hljs-symbol">'a</span>&gt; <span class="hljs-built_in">FnMut</span>(()) <span class="hljs-keyword">for</span> Closure_CountMut&lt;<span class="hljs-symbol">'a</span>&gt; {
    <span class="hljs-keyword">extern</span> <span class="hljs-string">"rust-call"</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">call_mut</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, _args: ()) {
        *<span class="hljs-keyword">self</span>.count_ref += <span class="hljs-number">1</span>;
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"count: {}"</span>, *<span class="hljs-keyword">self</span>.count_ref);
    }
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> count = <span class="hljs-number">0</span>;
    <span class="hljs-comment">// The closure is constructed</span>
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> increment = Closure_CountMut {
        count_ref: &amp;<span class="hljs-keyword">mut</span> count,
    };

    <span class="hljs-comment">// When we call it, it calls `call_mut`</span>
    increment.call_mut(());
    increment.call_mut(());
}
</code></pre>
<p>You can say that closure is <strong>syntactic sugar</strong> for an <strong>anonymous struct</strong> that holds the captured variables.</p>
<p>This is all done <strong>automatically</strong> by the compiler, but understanding this model helps clarify why closures have their particular capturing rules and trait bounds.</p>
<h2 id="heading-summary">Summary</h2>
<p>In summary, I would say if you need a small piece of logic that depends on local variables, but you don’t want to define a whole new named function. That’s exactly where <strong>closures</strong> come in. A closure is essentially an <strong>anonymous function</strong> that <strong>automatically captures</strong> variables from the scope in which it’s defined. Sometimes it merely borrows these variables (immutably or mutably), and other times it takes full ownership—Rust decides which strategy to use based on how you interact with those variables.</p>
<p>Once created, the closure acts like a callable object, implementing one or more of the function traits—<code>Fn</code>, <code>FnMut</code>, or <code>FnOnce</code>—depending on whether it only reads, mutates, or consumes its captured data. In cases where a closure doesn’t capture anything at all, the compiler can even <strong>coerce</strong> it into a plain function pointer.</p>
<p>Under the hood, Rust constructs an <strong>anonymous struct</strong> to hold whatever variables the closure captures, then it implements the relevant trait methods for that struct. Most of the time, these traits are derived automatically by the compiler.</p>
<p>Ultimately, this allows you to write concise, powerful inline functions that interact seamlessly with their surrounding environment—without ever losing track of Rust’s safety and performance guarantees. When it comes to performance, the use of closures in Rust is truly remarkable. Closures are designed to be efficient and fast, allowing you to write code that executes quickly without sacrificing safety or functionality. The Rust compiler is highly optimized for closures.</p>
]]></content:encoded></item><item><title><![CDATA[Immutability]]></title><description><![CDATA[Immutability is a cool concept in programming that C++ questions with "why?" It means that once you create a variable or object, you can't change its state. This idea somewhat opposes object-oriented concepts, yet it's crucial for writing clean, main...]]></description><link>https://siddharthqs.com/immutability</link><guid isPermaLink="true">https://siddharthqs.com/immutability</guid><category><![CDATA[Rust]]></category><category><![CDATA[C++]]></category><category><![CDATA[Java]]></category><category><![CDATA[immutable]]></category><dc:creator><![CDATA[Siddharth]]></dc:creator><pubDate>Tue, 04 Feb 2025 05:59:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/2LO0CkTMFCg/upload/542a2ee56b3819a7a39d50822aec2ce7.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Immutability is a cool concept in programming that C++ questions with "why?" It means that once you create a variable or object, you can't change its state. This idea somewhat opposes object-oriented concepts, yet it's crucial for writing clean, maintainable, and concurrency-friendly code. An immutable data structure can't be changed directly—any operation that seems to change it actually creates a new object or structure with the updated value, leaving the original unchanged. Different programming languages like Rust, C++, and Java have their own methods for handling immutability.</p>
<h2 id="heading-immutability-in-rust"><strong>Immutability in Rust</strong></h2>
<p>In Rust, immutability is a core feature and is enforced by the language's ownership and borrowing system. Variables are immutable by default. Once a value is assigned to a variable, it cannot be changed unless explicitly declared as mutable.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> x = <span class="hljs-number">5</span>; <span class="hljs-comment">// x is immutable</span>
<span class="hljs-comment">// x = 6; // This would cause a compile-time error</span>
<span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> y = <span class="hljs-number">10</span>; <span class="hljs-comment">// y is mutable</span>
y = <span class="hljs-number">20</span>; <span class="hljs-comment">// This is allowed</span>
</code></pre>
<p>Rust's immutability ensures thread safety and prevents data races. Immutable data can be shared across threads without the risk of concurrent modification. Rust's borrow checker enforces rules around mutable and immutable references to ensure memory safety.</p>
<p>Rust’s <strong>borrowing</strong> system ensures memory safety:</p>
<ul>
<li><p>Any number of <strong>immutable references</strong> (<code>&amp;T</code>) to a resource is allowed simultaneously.</p>
</li>
<li><p>You can have <em>either</em> a single <strong>mutable reference</strong> (<code>&amp;mut T</code>) <em>or</em> any number of immutable references, but not both at the same time.</p>
</li>
</ul>
<p>If you have a struct instance that is immutable, then its fields are also immutable—you can't change them.</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Point</span></span> {
    x: <span class="hljs-built_in">i32</span>,
    y: <span class="hljs-built_in">i32</span>,
}
<span class="hljs-keyword">let</span> p = Point { x: <span class="hljs-number">1</span>, y: <span class="hljs-number">2</span> }; <span class="hljs-comment">// p is immutable</span>
<span class="hljs-comment">// p.x = 3; // This would cause a compile-time error</span>
</code></pre>
<h2 id="heading-immutability-in-c"><strong>Immutability in C++</strong></h2>
<p>C++ does not enforce immutability by default, but it provides tools to achieve it. Variables are mutable unless explicitly marked as <code>const</code>. The <code>const</code> keyword is used to declare immutable variables or pointers.</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> x = <span class="hljs-number">5</span>; <span class="hljs-comment">// x is immutable</span>
<span class="hljs-comment">// x = 6; // This would cause a compile-time error</span>
</code></pre>
<p>In C++, you can mark member functions as <code>const</code> to indicate that they do not modify the object's state.</p>
<pre><code class="lang-cpp"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Point</span> {</span>
<span class="hljs-keyword">public</span>:
    <span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">getX</span><span class="hljs-params">()</span> <span class="hljs-keyword">const</span> </span>{ <span class="hljs-keyword">return</span> x; } <span class="hljs-comment">// This function does not modify the object</span>
<span class="hljs-keyword">private</span>:
    <span class="hljs-keyword">int</span> x;
};
</code></pre>
<h2 id="heading-immutability-in-java"><strong>Immutability in Java</strong></h2>
<p>Java provides immutability through the <code>final</code> keyword and immutable classes. The <code>final</code> keyword is used to declare immutable variables, methods, or classes.</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> x = <span class="hljs-number">5</span>; <span class="hljs-comment">// x is immutable</span>
<span class="hljs-comment">// x = 6; // This would cause a compile-time error</span>
</code></pre>
<p>In Java, immutable classes are created by making all fields <code>final</code> and not providing setters.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Point</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> x;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> y;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Point</span><span class="hljs-params">(<span class="hljs-keyword">int</span> x, <span class="hljs-keyword">int</span> y)</span> </span>{
        <span class="hljs-keyword">this</span>.x = x;
        <span class="hljs-keyword">this</span>.y = y;
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getX</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> x; }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getY</span><span class="hljs-params">()</span> </span>{ <span class="hljs-keyword">return</span> y; }
}
</code></pre>
<p>Embrace immutability where you can, and you’ll find your code more predictable, maintainable, and (in many cases) faster or easier to optimize.</p>
]]></content:encoded></item><item><title><![CDATA[Object-Oriented Thinking in Rust]]></title><description><![CDATA[Object-oriented programming, also called OOP, is a programming style that is dependent on the concept of objects. It is very popular and established. It is like designing and organizing your code by thinking of parts of your program as real-world obj...]]></description><link>https://siddharthqs.com/object-oriented-concepts-in-rust</link><guid isPermaLink="true">https://siddharthqs.com/object-oriented-concepts-in-rust</guid><category><![CDATA[Object Oriented Programming]]></category><category><![CDATA[Rust]]></category><dc:creator><![CDATA[Siddharth]]></dc:creator><pubDate>Mon, 20 Jan 2025 09:46:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/geNNFqfvw48/upload/b8f30188f6ba8fc3421fcfe68793d5fb.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Object-oriented programming</strong>, also called OOP, is a programming style that is dependent on the concept of <em>objects</em>. It is very popular and established. It is like designing and organizing your code by thinking of parts of your program as real-world objects. These objects bring together data (attributes) and functions (behaviors or methods) into one neat package that can communicate with each other. Every object has its own unique set of properties.</p>
<p>The building blocks of OOPs are attributes, methods, classes and object. The principles of OOPs are encapsulation, abstraction, inheritance and polymorphism. We will discuss these blocks and principles.</p>
<p>Rust isn't "object-oriented" in the usual inheritance-based way, but it offers tools—<strong>structs</strong>, <strong>impl</strong> blocks, and <strong>traits</strong>—that let you use many of the same design patterns: encapsulation, abstraction, and polymorphism.</p>
<p>In fact, Rust's approach is very close to object oriented way of thinking, can help you create more maintainable and strong systems.</p>
<h1 id="heading-encapsulation">Encapsulation</h1>
<p>Encapsulation is a core principle of object-oriented programming (OOP). It refers to bundling data (fields/attributes) and behavior (methods) together. In Rust, this is done by defining structs (similar to classes in other programming languages). Beyond just packaging data, encapsulation also involves hiding an object's internal state and implementation details, while providing a clear and accessible way to interact with it. In many traditional OOP languages like Java, C#, and C++, encapsulation is achieved using private fields (attributes) and public methods (getters, setters, business logic) to control access to these fields.</p>
<h2 id="heading-structs">Structs</h2>
<p>In classical OO languages:</p>
<ul>
<li><p>A <strong>class</strong> is a blueprint that defines the data (fields or attributes) and behaviors (methods).</p>
</li>
<li><p>An <strong>object</strong> is an instance of a class.</p>
</li>
</ul>
<p>In Rust, <code>struct</code>s can be used to group related data (similar to fields in a class). Along with <code>impl</code> blocks, which define associated functions and methods, <code>struct + impl</code> can serve a similar role to classes.</p>
<p><strong>Attributes</strong> are variables that represent the state of the object. In the below example future contract attributes represent its state. In other words attributes (or fields) refer to the data contained within an object.</p>
<h3 id="heading-example-a-basic-future-contract-struct">Example: A Basic Future Contract Struct</h3>
<p>A futures contract has attributes such as:</p>
<ul>
<li><p>The <strong>underlying asset</strong> (e.g., a commodity, stock index)</p>
</li>
<li><p>The <strong>quantity</strong> or number of units</p>
</li>
<li><p>The <strong>maturity date</strong></p>
</li>
<li><p>The <strong>entry price</strong> or the price at which the contract was agreed</p>
</li>
</ul>
<p>Here’s an example of how we can represent these attributes in Rust:</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">FutureContract</span></span> {
    underlying: <span class="hljs-built_in">String</span>,
    quantity: <span class="hljs-built_in">u64</span>,
    maturity_date: <span class="hljs-built_in">String</span>,
    entry_price: <span class="hljs-built_in">f64</span>,
}
</code></pre>
<p>This <code>FutureContract</code> struct holds all the relevant data for our futures contract. It’s analogous to defining a class with four attributes in an OO language.</p>
<p>We can create <strong>instances</strong> of a <code>struct</code> (akin to objects) by calling the struct’s name with the field values.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> future = FutureContract {
        underlying: <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"Crude Oil"</span>),
        quantity: <span class="hljs-number">100</span>,
        maturity_date: <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"2025-12-31"</span>),
        entry_price: <span class="hljs-number">60.50</span>,
    };

    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Created a future: {:?}"</span>, future);
}

Created a future: FutureContract { underlying: <span class="hljs-string">"Crude Oil"</span>, quantity: <span class="hljs-number">100</span>, maturity_date: <span class="hljs-string">"2025-12-31"</span>, entry_price: <span class="hljs-number">60.5</span> }
</code></pre>
<p>Here, <code>future</code> is an <strong>instance</strong> of <code>FutureContract</code>, just as an object would be an instance of a class in a classical OO paradigm.</p>
<p>Rust ensures that objects (instances of structs) are in a valid state after they are created. In an object-oriented way of thinking, an object must have a state; it cannot exist without a valid state. For example, if you create a point with x-axis and y-axis for a 2D coordinate system, a point object must have valid coordinates. You cannot create a point where you know the x-coordinate but the y-coordinate is unknown. Rust provides this by default. In C# you can achieve this using the required modifier.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">point</span></span>{
    x:<span class="hljs-built_in">i64</span> ,
    y: <span class="hljs-built_in">i64</span>
}
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> a = point{x:<span class="hljs-number">1</span>};
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Created a point: {:?}"</span>, a);
}
</code></pre>
<pre><code class="lang-rust">error[E0063]: missing field `y` <span class="hljs-keyword">in</span> initializer of `point`
 --&gt; src/main.rs:<span class="hljs-number">8</span>:<span class="hljs-number">13</span>
  |
<span class="hljs-number">8</span> |     <span class="hljs-keyword">let</span> a = point{x:<span class="hljs-number">1</span>};
  |             ^^^^^ missing `y`
</code></pre>
<p>If we try to create a point without y coordinate we get compile time error.</p>
<h2 id="heading-methods-and-associated-functions">Methods and Associated Functions</h2>
<p>In many OO languages, methods are defined within the class. Rust does not store methods within structs but uses <code>impl</code> blocks (implementation blocks) to define methods associated with a given struct.</p>
<p>Let’s add a <strong>constructor</strong>-like function (commonly named <code>new</code> in Rust). Rust does not have constructors in the classical sense. Instead, Rust uses <strong>associated functions</strong> (often called “factory” or “constructor-like” functions, typically named <code>new</code>) within an <code>impl</code> block to initialize structs.</p>
<p>Another method to <strong>calculate the contract’s notional value</strong> (quantity times entry price) and a method to <strong>settle</strong> the contract.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span> FutureContract {
    <span class="hljs-comment">/// Associated function (like a constructor)</span>
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>(underlying: &amp;<span class="hljs-built_in">str</span>, quantity: <span class="hljs-built_in">u64</span>, maturity_date: &amp;<span class="hljs-built_in">str</span>, entry_price: <span class="hljs-built_in">f64</span>) -&gt; <span class="hljs-keyword">Self</span> {
        FutureContract {
            underlying: <span class="hljs-built_in">String</span>::from(underlying),
            quantity,
            maturity_date: <span class="hljs-built_in">String</span>::from(maturity_date),
            entry_price,
        }
    } 
    <span class="hljs-comment">/// Calculate the notional value of the future</span>
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">calculate_notional</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span> {
        <span class="hljs-keyword">self</span>.quantity <span class="hljs-keyword">as</span> <span class="hljs-built_in">f64</span> * <span class="hljs-keyword">self</span>.entry_price
    }
    <span class="hljs-comment">/// Some method representing contract settlement</span>
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">settle</span></span>(&amp;<span class="hljs-keyword">self</span>, settlement_price: <span class="hljs-built_in">f64</span>) -&gt; <span class="hljs-built_in">f64</span> {
        <span class="hljs-comment">// Gain or loss = (Settlement price - Entry price) * Quantity</span>
        <span class="hljs-keyword">let</span> pnl = (settlement_price - <span class="hljs-keyword">self</span>.entry_price) * <span class="hljs-keyword">self</span>.quantity <span class="hljs-keyword">as</span> <span class="hljs-built_in">f64</span>;
        pnl
    }
}
</code></pre>
<p>To define the function within the context of <code>FutureContract</code>, we start an <code>impl</code> (implementation) block for <code>FutureContract</code>. Everything within this <code>impl</code> block will be associated with the <code>FutureContract</code> type.</p>
<p>All functions defined within an <code>impl</code> block are called <em>associated functions</em> because they’re associated with the type named after the <code>impl</code>. The associated functions that take self as parameters are called <strong>methods</strong> because they need instance of the struct. Associated functions that aren’t methods (don’t need self in parameters) are often used for constructors that will return a new instance of the struct. These are often called <code>new</code>, but <code>new</code> isn’t a special name and isn’t built into the language. The new function in our struct doesn’t take self and act as a constructor.</p>
<p>The <code>Self</code> keywords in the return type and in the body of the function are aliases for the type that appears after the <code>impl</code> keyword, which in this case is <code>FutureContract</code>. To call this associated function, we use the <code>::</code> syntax with the struct name.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> oil_future = FutureContract::new(<span class="hljs-string">"Crude Oil"</span>, <span class="hljs-number">100</span>, <span class="hljs-string">"2025-12-31"</span>, <span class="hljs-number">60.50</span>);
    <span class="hljs-keyword">let</span> notional = oil_future.calculate_notional();
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Notional value: ${:.2}"</span>, notional);
    <span class="hljs-keyword">let</span> pnl = oil_future.settle(<span class="hljs-number">65.00</span>);
    <span class="hljs-keyword">if</span> pnl &gt; <span class="hljs-number">0.0</span> {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Profit: ${:.2}"</span>, pnl);
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Loss: ${:.2}"</span>, pnl.abs());
    }
}
</code></pre>
<h3 id="heading-self-self-and-ampself-in-methods"><code>Self</code>, <code>self</code> and <code>&amp;self</code> in Methods</h3>
<p><code>Self</code> (capital “S”) refers to the type <strong>within</strong> an <code>impl</code> block. For instance, in our <code>impl FutureContract { ... }</code> block, <code>Self</code> is an alias for <code>FutureContract</code>. Typically used in <strong>associated functions</strong> (which do not take a <code>self</code> parameter) to construct or return an instance of the same type, for example, the <code>new</code> function in <code>impl FutureContract { ... }</code>. Here, <code>Self</code> is simply <code>FutureContract</code>. If you rename the struct, you won’t need to update the type references in the methods—<code>Self</code> will remain valid as it automatically refers to the type in the current <code>impl</code>.</p>
<p>Additionally, you can also see <code>Self</code> used as a return type in methods that consume <code>self</code> and return another struct of the same type, or partial transformations:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span> FutureContract {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">into_option</span></span>(<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">Option</span>&lt;<span class="hljs-keyword">Self</span>&gt; {
        <span class="hljs-comment">// Example of returning an Option of Self.</span>
        <span class="hljs-literal">Some</span>(<span class="hljs-keyword">self</span>)
    }
}
</code></pre>
<p>Here, <code>Option&lt;Self&gt;</code> could also be written as <code>Option&lt;FutureContract&gt;</code>.</p>
<p>Rust requires us to explicitly declare how we want to receive the instance: (<code>self</code>), by immutable reference (<code>&amp;self</code>), or by mutable reference (<code>&amp;mut self</code>).</p>
<h3 id="heading-ampself-immutable-reference"><code>&amp;self</code> — Immutable Reference</h3>
<p>When a method signature takes <code>&amp;self</code>, it borrows the struct <strong>immutably</strong>. This means the method can <em>read</em> the fields of the struct but cannot modify them. <code>calculate_notional</code> borrows <code>self</code> immutably, we can call it multiple times on the same instance, even simultaneously, as long as we don’t try to have mutable reference.</p>
<h3 id="heading-self-ownership-transfer"><code>self</code> — Ownership Transfer</h3>
<p>A method that takes <code>self</code> literally <strong>consumes</strong> the struct instance. After calling this method, the caller loses ownership unless something is returned.</p>
<h3 id="heading-ampmut-self-mutable-reference"><code>&amp;mut self</code> — Mutable Reference</h3>
<p>A method with <code>&amp;mut self</code> borrows the instance <strong>mutably</strong>, allowing the method to modify the struct’s fields.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span> FutureContract {
    <span class="hljs-comment">// A method that mutates the struct</span>
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">update_price</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, new_price: <span class="hljs-built_in">f64</span>) {
        <span class="hljs-keyword">self</span>.entry_price = new_price;
    }
}
</code></pre>
<p>Only one mutable reference to a given object can exist at a time, enforcing Rust’s <strong>borrow-checker</strong> rules.</p>
<p>The self is similar to self in Python, in both Python and Rust, “self” is the way you reference the current instance of a type. Both are explicit in the sense that they appear in the method signature. Rust requires you to be explicit about the <strong>ownership and borrowing</strong> (<code>self</code>, <code>&amp;self</code>, <code>&amp;mut self</code>). In Python, you can read and write to attributes through <code>self</code> without any explicit ownership or mutability rules. Rust enforces these constraints via the type system.</p>
<h3 id="heading-associated-functions-vs-static-methods-in-other-languages">Associated Functions vs. Static Methods in Other Languages</h3>
<p>In many object-oriented languages (e.g., Java, C#), you can mark a method as <code>static</code>, meaning it does not need an instance of the class to be called. This approach goes against the principles of OOP and can lead to less maintainable code. This might be why there is no specific <code>static</code> keyword for methods in Rust.</p>
<p>As we discussed earlier, associated functions that do not have a <code>self</code> parameter are called directly from the type, like this: <code>TypeName::function_name()</code>, instead of from an instance of the type. These associated functions are the closest equivalent to a "static method."</p>
<p>In JAVA/C#, you write <code>public static void foo() { ... }</code>, and call <a target="_blank" href="http://MyClass.foo"><code>MyClass.foo</code></a><code>()</code>. In C++, You might have <code>static void foo();</code> inside a class, and call <a target="_blank" href="http://MyClass.foo"><code>MyClass ::</code></a><code>foo()</code>;. Python uses <code>@staticmethod</code> decorator. In Rust, again, an associated function with no <code>self</code> is your “static method.”</p>
<p>You write:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span> MyStruct {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">foo</span></span>() {
        <span class="hljs-comment">// ...</span>
    }
}
</code></pre>
<p>and call <code>MyStruct::foo()</code><strong>.</strong></p>
<h3 id="heading-no-static-field-inside-a-struct">No static field inside a struct</h3>
<p>Using the <code>static</code> keyword on a class field means that all instances share that field, which isn't really in line with OOP principles and can lead to issues. Many object-oriented languages have moved away from OOP principles to include this feature. In <strong>Java/C#</strong>, the <code>static</code> keyword is used on a class field and is usually accessed with <code>ClassName.staticField</code>. C++ follows the same idea. Python doesn't have a static keyword but uses class attributes that all instances share. Luckily, Rust doesn't directly support a "static field inside a struct." It avoids this behavior and sticks more closely to OOP principles in this respect.</p>
<h2 id="heading-pub-keywords">pub keywords</h2>
<p>Encapsulation is also a practice of restricting direct access to some of the object's components. In Rust, this is done using <code>pub</code> (public) and private visibility modifiers.</p>
<h2 id="heading-overloading">Overloading</h2>
<p>When you have two or more methods with the same name but different parameters, that's called overloading. <strong>Rust does not support function or method overloading</strong> in the same way that languages like C++, Java, or C# do. In those languages, you can define multiple functions with the <em>same name</em> but different <em>parameter lists</em> or <em>types</em> (e.g., <code>foo(int x)</code> vs. <code>foo(double x)</code> vs. <code>foo(int x, int y)</code>).</p>
<p>Rust, however, <strong>disallows</strong> having two or more functions in the same scope.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">point</span></span>{
    x:<span class="hljs-built_in">i64</span> ,
    y:<span class="hljs-built_in">i64</span>
}
<span class="hljs-keyword">impl</span> point{
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">my_point</span></span>(){
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"my_point function with no parameter"</span>);
    }
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">my_point</span></span>(_x:<span class="hljs-built_in">i64</span>){
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"my_point function with int parameter"</span>);
    }
}
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> a = point{x:<span class="hljs-number">1</span>,y:<span class="hljs-number">2</span>};
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Created a point: {:?}"</span>, a);
    point::my_point();
}
</code></pre>
<p>Rust <strong>does not</strong> allow these two <code>my_point</code> methods to coexist, even though they have different signatures, because it doesn’t support method overloading by parameter signatures.</p>
<pre><code class="lang-rust">error[E0592]: duplicate definitions with name `my_point`
  --&gt; src/main.rs:<span class="hljs-number">10</span>:<span class="hljs-number">5</span>
   |
<span class="hljs-number">7</span>  |     <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">my_point</span></span>(){
   |     ------------- other definition <span class="hljs-keyword">for</span> `my_point`
...
<span class="hljs-number">10</span> |     <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">my_point</span></span>(_x:<span class="hljs-built_in">i64</span>){
   |     ^^^^^^^^^^^^^^^^^^^ duplicate definitions <span class="hljs-keyword">for</span> `my_point`
</code></pre>
<p>Some would argue that overloadimg makes code base more readable and manageable, but Rust don’t believe in this. Overloading can obscure which function is actually getting called, especially if conversions are implicit. Rust reduce confusion and make sure you have cleaner code. You can use some pattern to achieve this.</p>
<h1 id="heading-polymorphism">Polymorphism</h1>
<p>Polymorphism is a big idea in programming languages. It basically means "many forms." Depending on the situation, your functions can take on different forms and behave differently. For example, function overloading is one kind of polymorphism. Generics are another type, where a function or struct is written in a way that it can work with different types while still keeping everything type-safe, like this: <code>fn do_something&lt;T: SomeTrait&gt;(x: T) { ... }</code>.</p>
<p>In the context of object-oriented concepts, we're particularly interested in <strong>subtype polymorphism</strong> (often called <em>inheritance-based polymorphism</em> or <em>inclusion polymorphism</em>), where an object (or reference) of a <strong>subtype</strong> can be used anywhere its <strong>supertype</strong> is expected.</p>
<p>In classical OOP languages (e.g., Java, C#), subtype polymorphism typically relies on inheritance: a derived class “is a kind of” the base class and can be used in any context expecting the base. Rust does <strong>not</strong> support inheritance in that traditional sense, but it provides a powerful mechanism—<strong>trait objects</strong>—which enable <strong>runtime polymorphism</strong> (often called “dynamic dispatch”).</p>
<p>Rust uses <strong>traits</strong> to define shared behaviors or capabilities. In Rust, when we talk about subtype polymorphism, it means that if different concrete types implement the same trait, you can keep them in the same data structure or pass them to the same function by just referring to that <strong>trait</strong>.</p>
<h2 id="heading-traits">Traits</h2>
<p>Traits are fundamental feature in Rust that provide a way for shared behavior, abstraction and polymorphism. You can think of traits as interfaces in other programming languages. This is how The Rust Programming Language (“the Rust book”) defines traits:</p>
<blockquote>
<p><strong><em>A trait tells the Rust compiler about functionality a particular type has and can share with other types. We can use traits to define shared behavior in an abstract way. We can use trait bounds to specify that a generic can be any type that has certain behavior.</em></strong></p>
</blockquote>
<p>This is specially important as Rust is not an object-oriented language, in a traditional sense. Struct doesn't support inheritance.</p>
<h3 id="heading-define-a-trait"><strong>Define a Trait</strong></h3>
<p>Let's say we have a variety of financial instruments from different asset classes like equity, equity options, and interest rate derivatives. We need a few generic methods on all the contracts so that we can analyze the portfolio of trades. We define a trait named Contract with one method named npv. The may look like a virtual method in C++.</p>
<pre><code class="lang-rust">    <span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Contract</span></span> {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">npv</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span>;
    }
</code></pre>
<p>In this example, Contract is a trait that requires an implementing type to define the npv method. The npv method takes a reference to self and returns a f64 value.</p>
<h3 id="heading-implement-a-trait"><strong>Implement a Trait</strong></h3>
<p>Any type that implements the Contract trait must provide an implementation of the <code>npv</code> method. Here is an example of a struct named <code>EquityOption</code> that implements the <code>Contract</code> trait. <code>impl</code> keyword is used to implement traits for a struct. I believe the <code>impl</code> keyword is inspired by the <code>implements</code> keyword in Java.</p>
<pre><code class="lang-rust">    <span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">EquityOption</span></span> {
        <span class="hljs-keyword">pub</span> strike: <span class="hljs-built_in">f64</span>,
        <span class="hljs-keyword">pub</span> expiry: <span class="hljs-built_in">f64</span>,
        <span class="hljs-keyword">pub</span> is_call: <span class="hljs-built_in">bool</span>,
    }
    <span class="hljs-keyword">impl</span> Contract <span class="hljs-keyword">for</span> EquityOption {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">npv</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span> {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Calculating npv for EquityOption"</span>);
            <span class="hljs-number">0.0</span>
        }
    }
</code></pre>
<p>In this example, EquityOption is a struct that implements the Contract trait. If you're familiar with C++, it's like <code>class EquityOption: public Contract</code>. Now, let's create another struct called InterestRateSwap that also implements the Contract trait.</p>
<pre><code class="lang-rust">    <span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">InterestRateSwap</span></span> {
        <span class="hljs-keyword">pub</span> notional: <span class="hljs-built_in">f64</span>,
        <span class="hljs-keyword">pub</span> fixed_rate: <span class="hljs-built_in">f64</span>,
        <span class="hljs-keyword">pub</span> floating_rate: <span class="hljs-built_in">f64</span>,
    }
    <span class="hljs-keyword">impl</span> Contract <span class="hljs-keyword">for</span> InterestRateSwap {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">npv</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span> {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Calculating npv for InterestRateSwap"</span>);
            <span class="hljs-number">0.0</span>
        }
    }
</code></pre>
<p>We have totally different asset classes, EquityOption and InterestRateSwap, but they both implement the Contract trait. We can create a portfolio of equity options and interest rate swaps and calculate the net present value of the portfolio.</p>
<pre><code class="lang-rust">    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">calculate_portfolio_npv</span></span>(contracts: <span class="hljs-built_in">Vec</span>&lt;&amp;<span class="hljs-keyword">dyn</span> Contract&gt;) -&gt; <span class="hljs-built_in">f64</span> {
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> npv = <span class="hljs-number">0.0</span>;
        <span class="hljs-keyword">for</span> contract <span class="hljs-keyword">in</span> contracts {
            npv += contract.npv();
        }
        npv
    }
</code></pre>
<p>Here, <code>dyn</code> Contract is a trait object. This means we can pass a vector of any type that implements the Contract trait. This is an example of <strong>dynamic dispatch</strong>. We'll talk more about this when we dive into <code>dyn</code> in detail. Now, let's take a look at another implementation of the same function using static dispatch. Traits can also be used to set constraints on generic types, known as <strong>trait bounds</strong>. Here's an example of a generic function that calculates the net present value of a portfolio of contracts.</p>
<pre><code class="lang-rust">    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">calculate_portfolio_npv</span></span>&lt;T: Contract&gt;(contracts: <span class="hljs-built_in">Vec</span>&lt;T&gt;) -&gt; <span class="hljs-built_in">f64</span> {
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> npv = <span class="hljs-number">0.0</span>;
        <span class="hljs-keyword">for</span> contract <span class="hljs-keyword">in</span> contracts {
            npv += contract.npv();
        }
        npv
    }
</code></pre>
<p>In this example, T: Contract is a trait bound that specifies that T must implement the Contract trait. This is called static dispatch. The compiler generates a separate version of <code>calculate_portfolio_npv</code> for each type T used.</p>
<h3 id="heading-static-vs-dynamic-dispatch"><strong>Static vs Dynamic Dispatch</strong></h3>
<p>Rust support both static and dynamic dispatch.</p>
<ul>
<li><p>Static dispatch is resolved at compile time. The compiler knows the exact type at compile time and method calls are resolved during compilation.</p>
</li>
<li><p>Dynamic dispatch is resolved at runtime. The compiler doesn't know the exact type at compile time and method calls are resolved via virtual table (vtable), similar to virtual function in C++.</p>
</li>
</ul>
<p>Rust's traits are closely tied to its ownership and borrowing model, and it clearly distinguishes between static and dynamic dispatch.</p>
<h1 id="heading-inheritance">Inheritance</h1>
<p>Actually no inheritance, no <code>super</code> or “abstract class” or no deep class hierarchies. You can’t call a parent class method from a child; Rust’s approach is about <em>interfaces</em> and <em>implementations</em>. Inheritance in rust is only for traits. You can define a trait that inherits from another trait. Here is an example of a trait named Option that inherits from the Contract trait.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Option</span></span>: Contract {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">delta</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span>;
    }
</code></pre>
<p>In this example, Option is a trait that inherits from the Contract trait and requires an implementing type to define the delta method. If we have a struct named EquityOption that implements the Option trait, it must provide implementations of both the npv and delta methods by implementing respective traits.</p>
<pre><code class="lang-rust">    <span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">EquityOption</span></span> {
        <span class="hljs-keyword">pub</span> strike: <span class="hljs-built_in">f64</span>,
        <span class="hljs-keyword">pub</span> expiry: <span class="hljs-built_in">f64</span>,
        <span class="hljs-keyword">pub</span> is_call: <span class="hljs-built_in">bool</span>,
    }

    <span class="hljs-keyword">impl</span> Contract <span class="hljs-keyword">for</span> EquityOption {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">npv</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span> {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Calculating npv for EquityOption"</span>);
            <span class="hljs-number">0.0</span>
        }
    }

    <span class="hljs-keyword">impl</span> <span class="hljs-built_in">Option</span> <span class="hljs-keyword">for</span> EquityOption {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">delta</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span> {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Calculating delta for EquityOption"</span>);
            <span class="hljs-number">0.0</span>
        }
    }
</code></pre>
<p>If you implement the Option traits then you must implement the Contract trait as well, otherwise you have error like this:</p>
<pre><code class="lang-rust">    error[E0277]: the <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">bound</span></span> `EquityOption: Contract` is not unfulfilled
</code></pre>
<p>This is another example of trait bounds in Rust. It forces the implementing type to implement all the required traits.</p>
<h2 id="heading-default-implementations-of-traits"><strong>Default Implementations of Traits</strong></h2>
<p>You can provide default implementations for trait methods.</p>
<pre><code class="lang-rust">    <span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Contract</span></span> {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">npv</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span> {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Calculating npv for Contract"</span>);
            <span class="hljs-number">0.0</span>
        }
    }
</code></pre>
<p>In this example, Contract is a trait that provides a default implementation for the npv method. In this case, you don't have to provide the implementation of the npv method in the implementing type.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span> Contract <span class="hljs-keyword">for</span> EquityOption {}
</code></pre>
<h2 id="heading-multiple-trait-implementations"><strong>Multiple Trait Implementations</strong></h2>
<p>You can have only one implementation for each type.</p>
<pre><code class="lang-rust">    <span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Contract</span></span> {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">npv</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span>;
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">expiry</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span>;
    }
    <span class="hljs-keyword">impl</span> Contract <span class="hljs-keyword">for</span> EquityOption {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">npv</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span> {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Calculating npv for EquityOption"</span>);
            <span class="hljs-number">0.0</span>
        }
    }

    <span class="hljs-keyword">impl</span> Contract <span class="hljs-keyword">for</span> EquityOption {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">expiry</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span> {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Calculating expiry for EquityOption in days"</span>);
            <span class="hljs-number">0.0</span>
        }
    }
</code></pre>
<p>This will give you an error like this:</p>
<pre><code class="lang-rust">    error[E0119]: conflicting implementations of <span class="hljs-class"><span class="hljs-keyword">trait</span> `<span class="hljs-title">Contract</span></span>` <span class="hljs-keyword">for</span> <span class="hljs-class"><span class="hljs-keyword">type</span> `<span class="hljs-title">EquityOption</span></span>`
</code></pre>
<p>This prevents the ambiguity in the code. You can have multiple traits but only one implementation for each type.</p>
<h1 id="heading-abstraction">Abstraction</h1>
<p>Abstraction is a key idea in Object-Oriented Programming (OOP) that lets you hide complex implementation details and show only the essential features or functions to the user. In Rust, you achieve abstraction using traits, modules, and encapsulation.</p>
<p>Traits define a set of methods that a type must implement, allowing you to <strong>abstract over behavior</strong> without specifying the implementation.</p>
<h3 id="heading-modules-organizing-and-abstracting-code"><strong>Modules (Organizing and Abstracting Code)</strong></h3>
<p>Rust’s module system allows you to organize code into logical units and control visibility. By default, items in a module are private, and you can expose only what’s necessary using <code>pub</code>.</p>
]]></content:encoded></item><item><title><![CDATA[Traits]]></title><description><![CDATA[Traits are the most important topic to understand the design patterns in Rust.
Traits are fundamental feature in Rust that provide a way for shared behavior, 
abstraction and polymorphish.
You can think of traits as interfaces in other programming la...]]></description><link>https://siddharthqs.com/traits</link><guid isPermaLink="true">https://siddharthqs.com/traits</guid><category><![CDATA[Rust]]></category><category><![CDATA[Object Oriented Programming]]></category><category><![CDATA[polymorphism]]></category><category><![CDATA[abstraction]]></category><dc:creator><![CDATA[Siddharth]]></dc:creator><pubDate>Thu, 21 Nov 2024 08:41:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/wj1JEf6yqJI/upload/c6a4588f40838393dc15994ea997e255.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Traits are the most important topic to understand the design patterns in Rust.
Traits are fundamental feature in Rust that provide a way for shared behavior, 
abstraction and polymorphish.
You can think of traits as interfaces in other programming languages.
This is how The Rust Programming Language (“the Rust book”) defines traits:</p>
<blockquote>
<p>A trait tells the Rust compiler about functionality a particular type has and can share with other types. We can use traits to define shared behavior in an abstract way.
We can use trait bounds to specify that a generic can be any type that has certain behavior.</p>
</blockquote>
<p>This is specially important as Rust is not an object-oriented language, in a traditional sense.
Struct doesn't support inheritance. You can not define an abstract base struct and inherit to make a derived struct.
To achieve the polymorphism in Rust, you need a pointer (reference) that can hold references of any type that have shared behavior.
This is where traits come in.</p>
<h2 id="heading-define-a-trait">Define a Trait</h2>
<p>Let's say we have a variety of financial instruments from different asset classes like equity, 
equity options, and interest rate derivatives. 
We need a few generic methods on all the contracts so that we can analyze the portfolio of trades.
We define a trait named Contract with one method named npv. The may look like a virtual method in C++.</p>
<pre><code class="lang-rust">    <span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Contract</span></span> {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">npv</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span>;
    }
</code></pre>
<p>In this example, Contract is a trait that requires an implementing type to define the npv method.
The npv method takes a reference to self and returns a f64 value. </p>
<h2 id="heading-implement-a-trait">Implement a Trait</h2>
<p>Any type that implements the Contract trait must provide an implementation of the npv method.
Here is an example of a struct named EquityOption that implements the Contract trait.
impl keyword is used to implement traits for a struct. I think the impl keyword comes from implements keyword in Java.</p>
<pre><code class="lang-rust">    <span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">EquityOption</span></span> {
        <span class="hljs-keyword">pub</span> strike: <span class="hljs-built_in">f64</span>,
        <span class="hljs-keyword">pub</span> expiry: <span class="hljs-built_in">f64</span>,
        <span class="hljs-keyword">pub</span> is_call: <span class="hljs-built_in">bool</span>,
    }

    <span class="hljs-keyword">impl</span> Contract <span class="hljs-keyword">for</span> EquityOption {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">npv</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span> {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Calculating npv for EquityOption"</span>);
            <span class="hljs-number">0.0</span>
        }
    }
</code></pre>
<p>In this example, EquityOption is a struct that implements the Contract trait. If you are familiar with C++ then it is similar to
<code>class EquityOption: public Contract</code>.
Let's create one more struct named InterestRateSwap that implements the Contract trait.</p>
<pre><code class="lang-rust">    <span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">InterestRateSwap</span></span> {
        <span class="hljs-keyword">pub</span> notional: <span class="hljs-built_in">f64</span>,
        <span class="hljs-keyword">pub</span> fixed_rate: <span class="hljs-built_in">f64</span>,
        <span class="hljs-keyword">pub</span> floating_rate: <span class="hljs-built_in">f64</span>,
    }

    <span class="hljs-keyword">impl</span> Contract <span class="hljs-keyword">for</span> InterestRateSwap {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">npv</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span> {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Calculating npv for InterestRateSwap"</span>);
            <span class="hljs-number">0.0</span>
        }
    }
</code></pre>
<p>We have totally different asset classes, EquityOption and InterestRateSwap, but they both implement the Contract trait.
We can create a portfolio of equity options and interest rate swaps and calculate the net present value of the portfolio.</p>
<h3 id="heading-polymorphism-with-traits">Polymorphism with Traits</h3>
<pre><code class="lang-rust">    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">calculate_portfolio_npv</span></span>(contracts: <span class="hljs-built_in">Vec</span>&lt;&amp;<span class="hljs-keyword">dyn</span> Contract&gt;) -&gt; <span class="hljs-built_in">f64</span> {
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> npv = <span class="hljs-number">0.0</span>;
        <span class="hljs-keyword">for</span> contract <span class="hljs-keyword">in</span> contracts {
            npv += contract.npv();
        }
        npv
    }
</code></pre>
<p>Here, dyn Contract is a trade object.
We can pass a vector of any type that implements the Contract trait. This is example of dynamic dispatch.
We will discuss more shortly when discuss dyn in details. 
Let's understand see the another implementation of the same function with static dispatch.
Traits can also be used to impose constraints on generic types, known as trait bounds.
Here is an example of a generic function that calculates the net present value of a portfolio of contracts.</p>
<pre><code class="lang-rust">    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">calculate_portfolio_npv</span></span>&lt;T: Contract&gt;(contracts: <span class="hljs-built_in">Vec</span>&lt;T&gt;) -&gt; <span class="hljs-built_in">f64</span> {
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> npv = <span class="hljs-number">0.0</span>;
        <span class="hljs-keyword">for</span> contract <span class="hljs-keyword">in</span> contracts {
            npv += contract.npv();
        }
        npv
    }
</code></pre>
<p>In this example, T: Contract is a trait bound that specifies that T must implement the Contract trait. This is called static dispatch.
The compiler generates a separate version of calculate_portfolio_npv for each type T used.</p>
<h3 id="heading-static-vs-dynamic-dispatch">Static vs Dynamic Dispatch</h3>
<p>Rust support both static and dynamic dispatch. </p>
<ul>
<li>Static dispatch is resolved at compile time. The compiler knows the exact type at compile time and method calls are resolved during compilation.</li>
<li>Dynamci dispatch is resolved at runtime. The compiler doesn't know the exact type at compile time and method calls are resolved via virtual table (vtable), similar to virtual function in C++.</li>
</ul>
<p>Rust's traits are closed tied to its ownsership and borrowing model, and it distinguishes between static and dynamic dispatch explicitly.</p>
<h2 id="heading-inheritance-in-rust">Inheritance in Rust</h2>
<p>Inheritance in rust is onlt for traits. You can define a trait that inherits from another trait.
Here is an example of a trait named Option that inherits from the Contract trait.</p>
<pre><code class="lang-rust">    <span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Option</span></span>: Contract {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">delta</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span>;
    }
</code></pre>
<p>In this example, Option is a trait that inherits from the Contract trait 
and requires an implementing type to define the delta method. 
If we have a struct named EquityOption that implements the Option trait,
it must provide implementations of both the npv and delta methods by implementing respective traits.</p>
<pre><code class="lang-rust">    <span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">EquityOption</span></span> {
        <span class="hljs-keyword">pub</span> strike: <span class="hljs-built_in">f64</span>,
        <span class="hljs-keyword">pub</span> expiry: <span class="hljs-built_in">f64</span>,
        <span class="hljs-keyword">pub</span> is_call: <span class="hljs-built_in">bool</span>,
    }

    <span class="hljs-keyword">impl</span> Contract <span class="hljs-keyword">for</span> EquityOption {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">npv</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span> {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Calculating npv for EquityOption"</span>);
            <span class="hljs-number">0.0</span>
        }
    }

    <span class="hljs-keyword">impl</span> <span class="hljs-built_in">Option</span> <span class="hljs-keyword">for</span> EquityOption {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">delta</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span> {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Calculating delta for EquityOption"</span>);
            <span class="hljs-number">0.0</span>
        }
    }
</code></pre>
<p>If you implement the Option traits then you must implement the Contract trait as well, 
otherwise you have error like this:</p>
<pre><code class="lang-rust">    error[E0277]: the <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">bound</span></span> `EquityOption: Contract` is not unfulfilled
</code></pre>
<p>This is another example of trait bounds in Rust. It forces the implementing type to implement all the required traits.</p>
<h2 id="heading-default-implementations">Default Implementations</h2>
<p>You can provide default implementations for trait methods.</p>
<pre><code class="lang-rust">    <span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Contract</span></span> {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">npv</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span> {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Calculating npv for Contract"</span>);
            <span class="hljs-number">0.0</span>
        }
    }
</code></pre>
<p>In this example, Contract is a trait that provides a default implementation for the npv method.
In this case, you don't have to provide the implementation of the npv method in the implementing type.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span> Contract <span class="hljs-keyword">for</span> EquityOption {}
</code></pre>
<h3 id="heading-multiple-trait-implementations">Multiple Trait Implementations</h3>
<p>You can have only one implementation for each type. </p>
<pre><code class="lang-rust">    <span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Contract</span></span> {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">npv</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span>;
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">expiry</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span>;
    }
    <span class="hljs-keyword">impl</span> Contract <span class="hljs-keyword">for</span> EquityOption {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">npv</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span> {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Calculating npv for EquityOption"</span>);
            <span class="hljs-number">0.0</span>
        }
    }

    <span class="hljs-keyword">impl</span> Contract <span class="hljs-keyword">for</span> EquityOption {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">expiry</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span> {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Calculating expiry for EquityOption in days"</span>);
            <span class="hljs-number">0.0</span>
        }
    }
</code></pre>
<p>This will give you an error like this:</p>
<pre><code class="lang-rust">    error[E0119]: conflicting implementations of <span class="hljs-class"><span class="hljs-keyword">trait</span> `<span class="hljs-title">Contract</span></span>` <span class="hljs-keyword">for</span> <span class="hljs-class"><span class="hljs-keyword">type</span> `<span class="hljs-title">EquityOption</span></span>`
</code></pre>
<p>This prevents the ambiguity in the code. You can have multiple traits but only one implementation for each type.</p>
<h2 id="heading-using-dyn-with-traits">Using dyn with Traits</h2>
<p>The dyn keyword is used to indicate a trait object, making it explict when dynamic dispatch is used.
A trait object is a pointer to some type that implements a trait, but exact type is not known at compile time.
Here is an example of a function that takes a trait object as an argument.</p>
<pre><code class="lang-rust">    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">calculate_npv</span></span>(contract: &amp;<span class="hljs-keyword">dyn</span> Contract) -&gt; <span class="hljs-built_in">f64</span> {
        contract.npv()
    }
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
        <span class="hljs-keyword">let</span> equity_option = EquityOption {
            strike: <span class="hljs-number">100.0</span>,
            expiry: <span class="hljs-number">1.0</span>,
            is_call: <span class="hljs-literal">true</span>,
        };
        <span class="hljs-keyword">let</span> interest_rate_swap = InterestRateSwap {
            notional: <span class="hljs-number">1000000.0</span>,
            fixed_rate: <span class="hljs-number">0.05</span>,
            floating_rate: <span class="hljs-number">0.03</span>,
        };
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Equity Option NPV: {}"</span>, calculate_npv(&amp;equity_option));
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Interest Rate Swap NPV: {}"</span>, calculate_npv(&amp;interest_rate_swap));
    }
</code></pre>
<p>In this example, calculate_npv takes a reference to a trait object that implements the Contract trait.</p>
<h3 id="heading-using-dyn-with-box">Using dyn with Box</h3>
<p>You can also use the Box type to create a trait object.</p>
<pre><code class="lang-rust">    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
        <span class="hljs-keyword">let</span> equity_option = EquityOption {
            strike: <span class="hljs-number">100.0</span>,
            expiry: <span class="hljs-number">1.0</span>,
            is_call: <span class="hljs-literal">true</span>,
        };
        <span class="hljs-keyword">let</span> interest_rate_swap = InterestRateSwap {
            notional: <span class="hljs-number">1000000.0</span>,
            fixed_rate: <span class="hljs-number">0.05</span>,
            floating_rate: <span class="hljs-number">0.03</span>,
        };
        <span class="hljs-keyword">let</span> contract: <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> Contract&gt; = <span class="hljs-built_in">Box</span>::new(equity_option);
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Equity Option NPV: {}"</span>, contract.npv());
        <span class="hljs-keyword">let</span> contract = <span class="hljs-built_in">Box</span>::new(interest_rate_swap) <span class="hljs-keyword">as</span> <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> Contract&gt;;
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Interest Rate Swap NPV: {}"</span>, contract.npv());
    }
</code></pre>
<p>By boxing and casting it to Box, you create a trait object on the heap.</p>
<h2 id="heading-traits-with-generics">Traits with Generics</h2>
<h3 id="heading-blanket-implementations">Blanket Implementations</h3>
<p>Rust allows you to provide a blanket implementation for all types that satisfy a certain trait bound.
Here is an example of a blanket implementation.
We define two more trait DiscountFactorProvider and CashFlow.</p>
<pre><code class="lang-rust">    <span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">DiscountFactorProvider</span></span> {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">discount_factor</span></span>(&amp;<span class="hljs-keyword">self</span>, date: NaiveDate) -&gt; <span class="hljs-built_in">f64</span>;
    }
    <span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">CashFlow</span></span> {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">amount</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span>;
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">date</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; NaiveDate;
    }
</code></pre>
<p>We can implement Contract with CashFlow trait</p>
<pre><code class="lang-rust">    <span class="hljs-keyword">impl</span>&lt;T&gt; Contract <span class="hljs-keyword">for</span> T
    <span class="hljs-keyword">where</span>
        T: CashFlow + DiscountFactorProvider,
    {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">npv</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span> {
            <span class="hljs-keyword">let</span> df = <span class="hljs-keyword">self</span>.discount_factor(<span class="hljs-keyword">self</span>.date());
            <span class="hljs-keyword">let</span> npv = <span class="hljs-keyword">self</span>.amount() * df;
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Calculating NPV using CashFlow and DiscountFactorProvider traits."</span>);
            npv
        }
    }
</code></pre>
<p>Any type implementing both CashFlow and DiscountFactorProvider will have npv implementation.
Let's consider another example:
Suppose you work on equity asset class and other team worked on fixed income asset class.
Now your teams wants to do the cross asset combine Bonds with Equity. Bond doesn't have the npv method instead it has price method and different traits.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Pricable</span></span> {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">price</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span>;
}
<span class="hljs-keyword">use</span> chrono::NaiveDate;
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Bond</span></span> {
    <span class="hljs-keyword">pub</span> face_value: <span class="hljs-built_in">f64</span>,
    <span class="hljs-keyword">pub</span> coupon_rate: <span class="hljs-built_in">f64</span>,
    <span class="hljs-keyword">pub</span> maturity: NaiveDate,
}
<span class="hljs-keyword">impl</span> Pricable <span class="hljs-keyword">for</span> Bond {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">price</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span> {
        <span class="hljs-comment">// Simplified pricing logic</span>
        <span class="hljs-keyword">self</span>.face_value * (<span class="hljs-number">1.0</span> + <span class="hljs-keyword">self</span>.coupon_rate)
    }
}
</code></pre>
<p>Since Bond implements Pricable, we can implement Contract for Bond by using the blanket implementation.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span>&lt;T&gt; Contract <span class="hljs-keyword">for</span> T
<span class="hljs-keyword">where</span>
    T: Pricable,
{
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">npv</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span> {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Calculating NPV using Pricable trait."</span>);
        <span class="hljs-keyword">self</span>.price()
    }
}
</code></pre>
<p>The npv method uses the price method from Pricable.</p>
<h3 id="heading-using-traits-with-generics-types">Using Traits with Generics Types</h3>
<p>You can use traits with generic types to provide more flexibility.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">EventHandler</span></span>&lt;E&gt; {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">handle_event</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, event: E);
}
</code></pre>
<p>EventHandler handles events of different types, useful in event-driven trading systems.
E is a generic type that represents the event type.
Here is an example of a struct named EventProcessor that implements the EventHandler trait.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">EventProcessor</span></span> {
    <span class="hljs-keyword">pub</span> name: <span class="hljs-built_in">String</span>,
}
<span class="hljs-keyword">impl</span>&lt;E&gt; EventHandler&lt;E&gt; <span class="hljs-keyword">for</span> EventProcessor {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">handle_event</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, event: E) {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{} handling event"</span>, <span class="hljs-keyword">self</span>.name);
    }
}
</code></pre>
<h2 id="heading-summary">Summary</h2>
<p>In summary, traits enables ad-hoc polymorphism in Rust, allowing functions to operate on any type,
as long as it satisfies certain constraints. 
Understanding how to define and use traits with generics is essential for leveraging Rust's strengths in abstraction and performance.
Generics allow your traits to work with a variety of data types and structures, enabling you to model complex behaviors in a flexible and efficient way.</p>
]]></content:encoded></item><item><title><![CDATA[Welcome to My C++ Notes: A Beginner's Guide!]]></title><description><![CDATA[Exercise 1: Find the Maximum Value in a Vector
std::vector<int> vec = {10, 20, 5, 30, 15};
auto max_iter = std::max_element(vec.begin(), vec.end());
if (max_iter != vec.end()) {
    std::cout << "The maximum value is " << *max_iter << "\n";
} else {
...]]></description><link>https://siddharthqs.com/welcome-to-my-c-notes-a-beginners-guide</link><guid isPermaLink="true">https://siddharthqs.com/welcome-to-my-c-notes-a-beginners-guide</guid><category><![CDATA[stl]]></category><dc:creator><![CDATA[Siddharth]]></dc:creator><pubDate>Sun, 10 Nov 2024 19:20:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/iOykDIkZLQw/upload/36d9d84ecb3a9e6ec0c2c5cf3717124f.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-exercise-1-find-the-maximum-value-in-a-vector">Exercise 1: Find the Maximum Value in a Vector</h1>
<pre><code class="lang-cpp"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; vec = {<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">5</span>, <span class="hljs-number">30</span>, <span class="hljs-number">15</span>};
<span class="hljs-keyword">auto</span> max_iter = <span class="hljs-built_in">std</span>::max_element(vec.begin(), vec.end());
<span class="hljs-keyword">if</span> (max_iter != vec.end()) {
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"The maximum value is "</span> &lt;&lt; *max_iter &lt;&lt; <span class="hljs-string">"\n"</span>;
} <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"The vector is empty.\n"</span>;
}
</code></pre>
<h1 id="heading-exercise-2-remove-the-last-element-from-the-vector">Exercise 2: Remove the last element from the vector</h1>
<p>To retrieve and remove the last element of a <code>std::vector</code> in C++, you can use a combination of the <code>back()</code> and <code>pop_back()</code> member functions. Alternatively using Iterators, you can use end and erase although this approach is less efficient for removing than pop_back();</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> lastElement = vec.back();  <span class="hljs-comment">// Get the last element 15</span>
vec.pop_back(); <span class="hljs-comment">// // Remove 15</span>
<span class="hljs-keyword">auto</span> it = vec.end() - <span class="hljs-number">1</span>;
<span class="hljs-keyword">int</span> lastElement = *it;
myVector.erase(it);
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Design Patterns in Rust with Algorithmic Trading Examples]]></title><description><![CDATA[What is design?
“Design” as a word is both an activity (verb) and a product (noun). As a verb it’s the process of thinking through and creating blueprints for classes, architectures, or systems. Design as a Noun is the artifact that results from the ...]]></description><link>https://siddharthqs.com/design-patterns-in-rust</link><guid isPermaLink="true">https://siddharthqs.com/design-patterns-in-rust</guid><category><![CDATA[algotrading]]></category><category><![CDATA[multithreading]]></category><category><![CDATA[Rust]]></category><dc:creator><![CDATA[Siddharth]]></dc:creator><pubDate>Sun, 03 Nov 2024 04:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730840203361/9158eec8-0f3f-4dce-bda8-6ee20207890a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-what-is-design">What is design?</h1>
<p>“Design” as a word is both an <strong>activity</strong> (verb) and a <strong>product</strong> (noun). As a verb it’s the process of thinking through and creating blueprints for classes, architectures, or systems. <strong>Design as a Noun</strong> is the <strong>artifact</strong> that results from the design activity. It might be a blueprint for a class, a system’s architectural diagram, or an entire ecosystem of interacting components.</p>
<p>When we talk about “design,” we’re not just envisioning static documents or diagrams; we’re imagining a <strong>dynamic ecosystem</strong>, much like a pond where water flows through pipes, where fish of different species interact, and where various environmental factors maintain a stable balance. A well-designed software system similarly has multiple components—classes, modules, services, or patterns—that function together harmoniously, each constrained by and supportive of the larger architecture. Similarly software design imposes conditions on components, dictating how they can or cannot interact.</p>
<p>In <strong>object-oriented software design</strong>, <strong>design patterns</strong> are like <strong>ecological rules</strong> or <strong>best practices</strong> that address common problems and encourage stable interactions:</p>
<ul>
<li><p><strong>Creational Patterns</strong>: Provide ways to instantiate objects</p>
</li>
<li><p><strong>Structural Patterns</strong>: Arrange classes and objects</p>
</li>
<li><p><strong>Behavioral Patterns</strong>: Govern how objects communicate and respond</p>
</li>
</ul>
<p>While design patterns solve <strong>localized design issues</strong>, <strong>software architecture design</strong> looks at the <strong>macro-level</strong>:</p>
<ul>
<li><p><strong>Layered Architectures</strong>: Separate responsibilities into layers</p>
</li>
<li><p><strong>Service-Oriented or Microservices</strong>: Break the system into independent yet interacting services</p>
</li>
<li><p><strong>Event-Driven Architectures</strong>: Focus on asynchronous communication and flows</p>
</li>
</ul>
<h2 id="heading-why-emphasize-design">Why Emphasize Design?</h2>
<ol>
<li><p><strong>Maintainability</strong>: A thoughtful design is easier to extend and adapt.</p>
</li>
<li><p><strong>Scalability</strong>: Well-chosen architectural decisions can accommodate growing demands without fundamental redesign.</p>
</li>
<li><p><strong>Reusability</strong>: Components, once designed, can be repurposed in future projects or domains.</p>
</li>
<li><p><strong>Predictability</strong>: Like a stable ecosystem, a well-architected system exhibits predictable behaviors, simplifying testing and debugging.</p>
</li>
</ol>
<p>The main focus of this blog is design patterns using object oriented concepts.</p>
<h1 id="heading-what-is-algorithmic-trading">What is Algorithmic Trading?</h1>
<p>Algorithmic trading models are automated trading strategies that use predefined rules, instructions and quantitative techniques to execute trades in financial markets. These are highly quantitative process used by large financial institutions. Now when technology touches every part of our lives, it's no surprise that algorithmic trading, once only used by big firms, is now available to individual traders and investors. This democratization has created many opportunities, but it also brings challenges and risks. This section will introduce you to algorithmic trading.</p>
<p>As executing large buy or sell order will push the price higher or lower that is also a cost for the firm. This cost associated with this is market impact cost. The algorithmics that aim to minimize the market impact cost along with other execution cost such as bid-ask spread are called order execution algorithms.</p>
<p>The algorithmic trading / systematic trading firms called buy-side develop algorithms / models aim to capitalize on market inefficiencies, trends or patterns to generate trading signals by analyzing vast amounts of data. There are also market making firms (called sell-side) that use trading strategy to foster market liquidity by continuously quoting both bid and ask prices for a specific security, effectively creating a two-way market. By actively participating in the market, market markers profit from the bid-ask spread and rebates.</p>
<p>At the heart of an algorithmic trading system are several essential components, including Order Management Systems (OMS), Execution Management Systems (EMS), backtesting frameworks and many more. Before exploring the design patterns, let's take a moment to discuss these components briefly to gain a better understanding of the design pattern examples. In addition to the algorithmic trading components, we will also cover essential terms related to the trading system. In this blog, as we implement various design pattern, we will learn Rust core concepts, data structures and algorithmic trading concepts.</p>
<h2 id="heading-order-management-systems-oms">Order management systems (OMS)</h2>
<p>Order management systems (OMS) play a crucial role in monitoring and executing trades for clients, such as portfolio managers and traders. For instance, when a portfolio manager decides to purchase 5,000 shares of NVDA at a limit price of $130 per share, they enter this order into the OMS. The OMS checks whether the order violates fund's concentration limit and if it does then alerts the PM. If all okay then analyzes current market conditions and routes the order to an exchange where the likelihood of execution at the desired price is highest. After execution, OMS sends trade details to the back-office system.</p>
<p>It's impressive how OMS can manage such high volumes of orders from various sources, control the flow, validate them, and ensure that trades are completed both efficiently and accurately.</p>
<h2 id="heading-order-execution-algorithms">Order Execution Algorithms</h2>
<h3 id="heading-arrival-price-implementation-shortfall">Arrival Price (Implementation Shortfall)</h3>
<p>The arrival price will attempt to achieve, over the course of the order, the bid/ask midpoint price at the time the order is submitted. The arrival algo keeps the hidden orders that will impact a high percentage of the average daily volume.</p>
<h3 id="heading-accumulate-distribute">Accumulate / Distribute</h3>
<p>This algo achieve the best price for a large volume order without being noticed in the market, and can be set up for high frequency trading by slicing the order into smaller randomly sized order increments that are released at random time intervals within a used defined time period.</p>
<h3 id="heading-twap-time-weighted-average-price">TWAP (Time Weighted Average Price)</h3>
<p>TWAP algorithms are designed to execute trades based on a rate proposed to time. It aims to achieve the time weighted average price calculated from the time of submitted order to the time it completes.</p>
<h3 id="heading-vwap-volume-weighted-average-price">VWAP (Volume Weighted Average Price)</h3>
<p>VWAP algo seeks to achieve the volume weighted average price, calculated from the time of submitted order. VWAP schedule is proportional to the historical intraday volume profile. This algo trade more at some time frame when the stock traded more historically at same time frame.</p>
<h3 id="heading-percentage-of-volume">Percentage of Volume</h3>
<p>The POV is an order execution trading strategy that allows trades to execute the desired percentage of the total market volume called participation rate over a specified period. It’s an adaptive strategy designed to adjust the order size dynamically based on prevailing or forecasted market volume in real-time.</p>
<h1 id="heading-the-solid-design-principles">The SOLID Design Principles</h1>
<p>Let's review the SOLID design principles since we might mention them while discussing design patterns. It's helpful to remember these principles when designing maintainable and scalable object-oriented systems.</p>
<ol>
<li><p>Single Responsibility Principle (SRP): A class should have only one reason to exist, meaning it should have only one job or responsibility. You should not overload your objects with two many responsibility, just create a new class for it.</p>
</li>
<li><p>Open/Closed Principle (OCP): Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification. This means you should be able to add new functionality without changing existing code.</p>
</li>
<li><p>Liskov Substitution Principle (LSP): Objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program. This ensures that a subclass can stand in for its superclass.</p>
</li>
<li><p>Interface Segregation Principle (ISP): Clients should not be forced to depend on interfaces they do not use. This means creating smaller, more specific interfaces rather than a large, general-purpose one.</p>
</li>
<li><p>Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules. Both should depend on abstractions. Additionally, abstractions should not depend on details. Details should depend on abstractions. This principle helps in reducing the coupling between different parts of a system.</p>
</li>
</ol>
<h1 id="heading-strategy-pattern">🔍Strategy Pattern</h1>
<p>The Strategy design pattern is a behavioral design pattern that enables selecting an algorithm's behavior at runtime. This pattern is based on composition. Lets see the definition from the “<a target="_blank" href="https://read.amazon.com/kp/embed?asin=B08P3X99QP&amp;preview=newtab&amp;linkCode=kpe&amp;ref_=kip_embed_taf_preview_8ZBSPVJ7NA44QJKAFE9X">Head First Design Pattern</a>”:</p>
<blockquote>
<p>The strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets algorithm vary independently from clients that use it.</p>
</blockquote>
<p>It is naturally useful in trading systems where algorithms need to switch between different execution methods. In this example, we'll implement a simplified trading system in Rust that executes orders using different strategies like <a target="_blank" href="https://siddharthqs.com/demystifying-order-execution-algorithms-in-trading-part-1-understanding-twap#heading-time-weighted-average-price-twap-algorithm">TWAP (Time-Weighted Average Price)</a>, VWAP (Volume-Weighted Average Price), and <a target="_blank" href="https://siddharthqs.com/the-pov-percentage-of-volume-algorithm">POV (Percentage of Volume)</a>. These are your execution strategies. You can choose one of the strategies based on certain factors or constraints.</p>
<h2 id="heading-structure">Structure</h2>
<ol>
<li>The <strong>Strategy</strong> interface is common to all concrete strategies. It declares a method the context uses to execute a strategy. We define a common interface for all execution strategies, the method <code>execute_order</code> that all execution strategies must implement.</li>
</ol>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">ExecutionStrategy</span></span> {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">execute_order</span></span>(&amp;<span class="hljs-keyword">self</span>, order_id: <span class="hljs-built_in">u32</span>, quantity: <span class="hljs-built_in">u32</span>);
}
</code></pre>
<ol start="2">
<li><p><strong>Concrete Strategies</strong> implement different variations of an algorithm the context uses. In this example, we write implementations of TWAP, VWAP, and POV strategies.</p>
<pre><code class="lang-rust"> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">TwapStrategy</span></span>;

 <span class="hljs-keyword">impl</span> ExecutionStrategy <span class="hljs-keyword">for</span> TwapStrategy {
     <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">execute_order</span></span>(&amp;<span class="hljs-keyword">self</span>, order_id: <span class="hljs-built_in">u32</span>, quantity: <span class="hljs-built_in">u32</span>) {
         <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Executing order {} using TWAP for {} units."</span>, order_id, quantity);
         <span class="hljs-comment">// Implement TWAP logic here</span>
     }
 }
 <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">VwapStrategy</span></span>;

 <span class="hljs-keyword">impl</span> ExecutionStrategy <span class="hljs-keyword">for</span> VwapStrategy {
     <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">execute_order</span></span>(&amp;<span class="hljs-keyword">self</span>, order_id: <span class="hljs-built_in">u32</span>, quantity: <span class="hljs-built_in">u32</span>) {
         <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Executing order {} using VWAP for {} units."</span>, order_id, quantity);
         <span class="hljs-comment">// Implement VWAP logic here</span>
     }
 }
 <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">PovStrategy</span></span> {
     participation_rate: <span class="hljs-built_in">f64</span>,
 }

 <span class="hljs-keyword">impl</span> ExecutionStrategy <span class="hljs-keyword">for</span> PovStrategy {
     <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">execute_order</span></span>(&amp;<span class="hljs-keyword">self</span>, order_id: <span class="hljs-built_in">u32</span>, quantity: <span class="hljs-built_in">u32</span>) {
         <span class="hljs-built_in">println!</span>(
             <span class="hljs-string">"Executing order {} using POV at {}% participation for {} units."</span>,
             order_id, <span class="hljs-keyword">self</span>.participation_rate * <span class="hljs-number">100.0</span>, quantity
         );
         <span class="hljs-comment">// Implement POV logic here</span>
     }
 }
</code></pre>
</li>
<li><p>The <strong>Context</strong> maintains a reference to one of the concrete strategies and communicates with this object only via the strategy interface. Here we write the <code>OrderExecutor</code> that holds a reference to a strategy and uses it to execute orders. The context calls the execution method on the linked strategy object each time it needs to run the algorithm. The context doesn’t know what type of strategy it works with or how the algorithm is executed.</p>
<pre><code class="lang-rust"> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">OrderExecutor</span></span> {
     strategy: <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> ExecutionStrategy&gt;,
 }

 <span class="hljs-keyword">impl</span> OrderExecutor {
     <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>(strategy: <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> ExecutionStrategy&gt;) -&gt; <span class="hljs-keyword">Self</span> {
         OrderExecutor { strategy }
     }
     <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">set_strategy</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, strategy: <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> ExecutionStrategy&gt;) {
         <span class="hljs-keyword">self</span>.strategy = strategy;
     }
     <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">execute</span></span>(&amp;<span class="hljs-keyword">self</span>, order_id: <span class="hljs-built_in">u32</span>, quantity: <span class="hljs-built_in">u32</span>) {
         <span class="hljs-keyword">self</span>.strategy.execute_order(order_id, quantity);
     }
 }
</code></pre>
</li>
<li><p>The <strong>Client</strong> creates a specific strategy object and passes it to the context. The context exposes a setter which lets clients replace the strategy associated with the context at runtime.</p>
<pre><code class="lang-rust"> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
     <span class="hljs-keyword">let</span> order_id = <span class="hljs-number">101</span>;
     <span class="hljs-keyword">let</span> quantity = <span class="hljs-number">1000</span>;

     <span class="hljs-comment">// Using TWAP Strategy</span>
     <span class="hljs-keyword">let</span> twap_strategy = <span class="hljs-built_in">Box</span>::new(TwapStrategy);
     <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> executor = OrderExecutor::new(twap_strategy);
     executor.execute(order_id, quantity);

     <span class="hljs-comment">// Switching to VWAP Strategy</span>
     <span class="hljs-keyword">let</span> vwap_strategy = <span class="hljs-built_in">Box</span>::new(VwapStrategy);
     executor.set_strategy(vwap_strategy);
     executor.execute(order_id+<span class="hljs-number">1</span>, quantity);

     <span class="hljs-comment">// Switching to POV Strategy</span>
     <span class="hljs-keyword">let</span> pov_strategy = <span class="hljs-built_in">Box</span>::new(PovStrategy {
         participation_rate: <span class="hljs-number">0.1</span>,
     });
     executor.set_strategy(pov_strategy);
     executor.execute(order_id+<span class="hljs-number">2</span>, quantity);
 }
</code></pre>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1728987984690/5be38c43-0217-409c-8b64-28e0c994fa0b.png" alt /></p>
<h3 id="heading-strategy-pattern-class-diagram">Strategy pattern Class Diagram</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731180519898/bcd0d8e0-fa2e-4a7d-b94a-47254946a5bc.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731180529910/705beb3f-5291-46fc-8bd2-1eef23093c9f.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-observer-pattern">👀Observer Pattern</h1>
<p>The <strong>Observer</strong> design pattern is a behavioral design pattern that enables an object, known as the <strong>Subject</strong>, to maintain a list of its dependents, called <strong>Observers</strong>, and automatically notify them of any state changes, typically by calling one of their methods. This pattern is particularly useful in <strong>Event-Driven Systems</strong>, when you need to notify multiple objects about events without tightly coupling them. The definition from the “<a target="_blank" href="https://read.amazon.com/kp/embed?asin=B08P3X99QP&amp;preview=newtab&amp;linkCode=kpe&amp;ref_=kip_embed_taf_preview_8ZBSPVJ7NA44QJKAFE9X">Head First Design Pattern</a>”:</p>
<blockquote>
<p>The observer pattern defines a one to many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.</p>
</blockquote>
<p>In the context of algorithmic trading , the Observer pattern can be applied to scenarios such as:</p>
<ul>
<li><p><strong>Market Data Feeds</strong>: Notifying trading strategies when new market data arrives.</p>
</li>
<li><p><strong>Order Execution Updates</strong>: Informing interested parties when an order is executed or its status changes.</p>
</li>
<li><p><strong>Price Alerts</strong>: Triggering alerts when certain price thresholds are crossed.</p>
</li>
<li><p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731186735232/d450cd06-7797-41c1-a7ad-c63a6204249c.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<h2 id="heading-structure-1">Structure</h2>
<ul>
<li><p><strong>Subject (Observable or Publisher)</strong>: The Subject issues events of interest to other objects. These events occur when the subject (publisher) changes its state or executes some behaviors. Subjects maintain a subscription infrastructure, list of observers and provides methods to attach, detach, and notify them.</p>
</li>
<li><p><strong>Observer (Subscriber)</strong>: The <strong>Observer</strong> interface declares the notification interface. In most cases, it consists of a single <code>update</code> method.</p>
</li>
<li><p><strong>Concrete Subject</strong>: Implements the subject interface and holds the state of interest.</p>
</li>
<li><p><strong>Concrete Observer</strong>: <strong>Concrete Observer</strong> perform some actions in response to notifications issued by the subject. All of these classes must implement the same interface so the subject isn’t coupled to concrete classes.</p>
</li>
</ul>
<p>Usually, subscribers need some contextual information to handle the update correctly. For this reason, publishers often pass some context data as arguments of the notification method. The publisher can pass itself as an argument, letting subscriber fetch any required data directly.</p>
<h2 id="heading-implementation-example">Implementation Example</h2>
<p>We will implement a simplified version of trading system using Rust where we have:</p>
<ul>
<li><p><strong>Market Data Feed</strong> (Subject): Provides live price updates for various financial instruments.</p>
</li>
<li><p><strong>Trading Strategies</strong> (Observers): React to market data updates to make trading decisions.</p>
</li>
</ul>
<p>Let's take a look at the UML diagram of this example and code implementation.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731186162192/068c2df5-3b08-459f-bb6c-aabb8718b8b6.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-observer-trait">Observer Trait</h3>
<p>The <code>Observer</code> trait declares the <code>update</code> method, which observers must implement.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::rc::Rc;
<span class="hljs-keyword">use</span> std::cell::RefCell;

<span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Observer</span></span> {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">update</span></span>(&amp;<span class="hljs-keyword">self</span>, instrument_id: &amp;<span class="hljs-built_in">str</span>, price: <span class="hljs-built_in">f64</span>);
}
</code></pre>
<h3 id="heading-implement-concrete-observers-trading-strategies">Implement Concrete Observers (Trading Strategies)</h3>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">MomentumStrategy</span></span> {
    name: <span class="hljs-built_in">String</span>,
    threshold: <span class="hljs-built_in">f64</span>,
}

<span class="hljs-keyword">impl</span> Observer <span class="hljs-keyword">for</span> MomentumStrategy {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">update</span></span>(&amp;<span class="hljs-keyword">self</span>, instrument_id: &amp;<span class="hljs-built_in">str</span>, price: <span class="hljs-built_in">f64</span>) {
        <span class="hljs-keyword">if</span> price &gt; <span class="hljs-keyword">self</span>.threshold {
            <span class="hljs-built_in">println!</span>(
                <span class="hljs-string">"{}: [{}] Price crossed above threshold! Price: {}"</span>,
                <span class="hljs-keyword">self</span>.name, instrument_id, price
            );
            <span class="hljs-comment">// Implement buy logic</span>
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-built_in">println!</span>(
                <span class="hljs-string">"{}: [{}] Price below threshold. Price: {}"</span>,
                <span class="hljs-keyword">self</span>.name, instrument_id, price
            );
            <span class="hljs-comment">// Implement hold or sell logic</span>
        }
    }
}

<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">MeanReversionStrategy</span></span> {
    name: <span class="hljs-built_in">String</span>,
    average_price: RefCell&lt;<span class="hljs-built_in">f64</span>&gt;,
}

<span class="hljs-keyword">impl</span> Observer <span class="hljs-keyword">for</span> MeanReversionStrategy {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">update</span></span>(&amp;<span class="hljs-keyword">self</span>, instrument_id: &amp;<span class="hljs-built_in">str</span>, price: <span class="hljs-built_in">f64</span>) {
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> avg = <span class="hljs-keyword">self</span>.average_price.borrow_mut();
        *avg = (*avg * <span class="hljs-number">0.9</span>) + (price * <span class="hljs-number">0.1</span>); <span class="hljs-comment">// Update moving average</span>
        <span class="hljs-keyword">if</span> price &lt; *avg {
            <span class="hljs-built_in">println!</span>(
                <span class="hljs-string">"{}: [{}] Price below average! Price: {}, Average: {:.2}"</span>,
                <span class="hljs-keyword">self</span>.name, instrument_id, price, *avg
            );
            <span class="hljs-comment">// Implement buy logic</span>
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-built_in">println!</span>(
                <span class="hljs-string">"{}: [{}] Price above average. Price: {}, Average: {:.2}"</span>,
                <span class="hljs-keyword">self</span>.name, instrument_id, price, *avg
            );
            <span class="hljs-comment">// Implement sell logic</span>
        }
    }
}
</code></pre>
<h3 id="heading-define-the-subject-trait">Define the Subject Trait</h3>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Subject</span></span> {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">attach</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, observer: Rc&lt;<span class="hljs-keyword">dyn</span> Observer&gt;);
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">detach</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, observer: &amp;Rc&lt;<span class="hljs-keyword">dyn</span> Observer&gt;);
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">notify</span></span>(&amp;<span class="hljs-keyword">self</span>);
}
</code></pre>
<h3 id="heading-implement-the-concrete-subject-market-data-feed">Implement the Concrete Subject (Market Data Feed)</h3>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">MarketDataFeed</span></span> {
    instrument_id: <span class="hljs-built_in">String</span>,
    observers: RefCell&lt;<span class="hljs-built_in">Vec</span>&lt;Rc&lt;<span class="hljs-keyword">dyn</span> Observer&gt;&gt;&gt;,
    price: RefCell&lt;<span class="hljs-built_in">f64</span>&gt;,
}

<span class="hljs-keyword">impl</span> MarketDataFeed {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>(instrument_id: &amp;<span class="hljs-built_in">str</span>) -&gt; <span class="hljs-keyword">Self</span> {
        MarketDataFeed {
            instrument_id: instrument_id.to_string(),
            observers: RefCell::new(<span class="hljs-built_in">Vec</span>::new()),
            price: RefCell::new(<span class="hljs-number">0.0</span>),
        }
    }
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">set_price</span></span>(&amp;<span class="hljs-keyword">self</span>, new_price: <span class="hljs-built_in">f64</span>) {
        *<span class="hljs-keyword">self</span>.price.borrow_mut() = new_price;
        <span class="hljs-keyword">self</span>.notify();
    }
}
<span class="hljs-keyword">impl</span> Subject <span class="hljs-keyword">for</span> MarketDataFeed {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">attach</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, observer: Rc&lt;<span class="hljs-keyword">dyn</span> Observer&gt;) {
        <span class="hljs-keyword">self</span>.observers.borrow_mut().push(observer);
    }
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">detach</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, observer: &amp;Rc&lt;<span class="hljs-keyword">dyn</span> Observer&gt;) {
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> observers = <span class="hljs-keyword">self</span>.observers.borrow_mut();
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Some</span>(pos) = observers.iter().position(|x| Rc::ptr_eq(x, observer)) {
            observers.remove(pos);
        }
    }
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">notify</span></span>(&amp;<span class="hljs-keyword">self</span>) {
        <span class="hljs-keyword">let</span> price = *<span class="hljs-keyword">self</span>.price.borrow();
        <span class="hljs-keyword">let</span> instrument_id = &amp;<span class="hljs-keyword">self</span>.instrument_id;
        <span class="hljs-keyword">for</span> observer <span class="hljs-keyword">in</span> <span class="hljs-keyword">self</span>.observers.borrow().iter() {
            observer.update(instrument_id, price);
        }
    }
}
</code></pre>
<h3 id="heading-client-code">Client Code</h3>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-comment">// Create market data feed for AAPL</span>
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> market_data_feed = MarketDataFeed::new(<span class="hljs-string">"AAPL"</span>);

    <span class="hljs-comment">// Create observers</span>
    <span class="hljs-keyword">let</span> momentum_strategy: Rc&lt;<span class="hljs-keyword">dyn</span> Observer&gt; = Rc::new(MomentumStrategy {
        name: <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"MomentumStrategy"</span>),
        threshold: <span class="hljs-number">150.0</span>,
    });

    <span class="hljs-keyword">let</span> mean_reversion_strategy: Rc&lt;<span class="hljs-keyword">dyn</span> Observer&gt; = Rc::new(MeanReversionStrategy {
        name: <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"MeanReversionStrategy"</span>),
        average_price: RefCell::new(<span class="hljs-number">145.0</span>),
    });

    <span class="hljs-comment">// Attach observers</span>
    market_data_feed.attach(momentum_strategy.clone());
    market_data_feed.attach(mean_reversion_strategy.clone());

    <span class="hljs-comment">// Simulate market data updates</span>
    <span class="hljs-keyword">let</span> price_updates = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">148.0</span>, <span class="hljs-number">151.0</span>, <span class="hljs-number">149.5</span>, <span class="hljs-number">152.5</span>, <span class="hljs-number">147.0</span>];

    <span class="hljs-keyword">for</span> price <span class="hljs-keyword">in</span> price_updates {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"\nMarketDataFeed [{}]: New price is {}"</span>, <span class="hljs-string">"AAPL"</span>, price);
        market_data_feed.set_price(price);
    }

    <span class="hljs-comment">// Detach momentum strategy</span>
    market_data_feed.detach(&amp;momentum_strategy);

    <span class="hljs-comment">// More updates</span>
    <span class="hljs-keyword">let</span> more_price_updates = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">153.0</span>, <span class="hljs-number">146.5</span>];

    <span class="hljs-keyword">for</span> price <span class="hljs-keyword">in</span> more_price_updates {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"\nMarketDataFeed [{}]: New price is {}"</span>, <span class="hljs-string">"AAPL"</span>, price);
        market_data_feed.set_price(price);
    }
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1729405204844/ca56c96f-f7e3-4f72-8d32-76844c57d060.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-notes-on-rust-implementation">Notes on Rust Implementation</h3>
<ul>
<li><p><strong>Reference Counting (</strong><code>Rc</code>): Used to allow multiple ownership of observers by the subject.</p>
</li>
<li><p><strong>Interior Mutability (</strong><code>RefCell</code>): Allows us to mutate data even when it is wrapped in an immutable reference, which is necessary when observers need to update their internal state upon receiving updates.</p>
</li>
<li><p><strong>Trait Objects (</strong><code>dyn Trait</code>): Trait objects like <code>dyn Observer</code> allow for dynamic dispatch in Rust. They allow the subject to hold a collection of different types that implement the same trait.</p>
</li>
</ul>
<p>In Rust, comparing trait objects (<code>dyn Observer</code>) directly is not straightforward because trait objects do not implement <code>PartialEq</code> by default. We use <code>Rc::ptr_eq</code> to compare the pointers of the <code>Rc</code> smart pointers, which checks if they point to the same allocation.</p>
<p>In the line, if we don’t explicitly say the type Rc&lt;dyn Observer&gt; then momentum_strategy will be of type Rc&lt;MomentumStrategy&gt; and it will be fine for attach method however not work with detach method.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> momentum_strategy: Rc&lt;<span class="hljs-keyword">dyn</span> Observer&gt; = Rc::new(MomentumStrategy{...});
</code></pre>
<p>In Rust, even though <code>MomentumStrategy</code> implements the <code>Observer</code> trait, <code>Rc&lt;MomentumStrategy&gt;</code> and <code>Rc&lt;dyn Observer&gt;</code> are different types and are not directly interchangeable.</p>
<p>💡Note: The <code>Rc::ptr_eq</code> function requires that both <code>Rc</code> pointers have the same type parameter. By ensuring that both <code>Rc</code> pointers are of type <code>Rc&lt;dyn Observer&gt;</code>, we satisfy this requirement.</p>
<p>Rust can automatically coerce a reference to a concrete type into a reference to a trait object if the type implements the trait. This is what happens when you assign <code>Rc::new(MomentumStrategy { /* fields */ })</code> to a variable of type <code>Rc&lt;dyn Observer&gt;</code>.</p>
<h1 id="heading-decorator-pattern">Decorator Pattern</h1>
<p>The <strong>Decorator Pattern</strong> is a structural design pattern that allows behavior to be added to individual objects dynamically without affecting the behavior of other objects from the same class. The definition from the “<a target="_blank" href="https://read.amazon.com/kp/embed?asin=B08P3X99QP&amp;preview=newtab&amp;linkCode=kpe&amp;ref_=kip_embed_taf_preview_8ZBSPVJ7NA44QJKAFE9X">Head First Design Pattern</a>”:</p>
<blockquote>
<p>The decorator pattern attaches additional responsibilities to an object dynamically. Decorators provides a flexible alternative to subclassing for extending functionality.</p>
</blockquote>
<h2 id="heading-structure-2">Structure</h2>
<ul>
<li><p><strong>Component Interface</strong>: Defines the interface for objects that can have responsibilities added to them dynamically.</p>
</li>
<li><p><strong>Concrete Component</strong>: The original object to which additional responsibilities are added.</p>
</li>
<li><p><strong>Decorator</strong>: Abstract class that implements the component interface and contains a reference to a component object.</p>
</li>
<li><p><strong>Concrete Decorators</strong>: Extend the functionality of the component by overriding methods and adding additional behaviors.</p>
</li>
</ul>
<h3 id="heading-uml-diagram">UML Diagram</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730868338774/eaeec0fb-6af5-4392-9c77-9dc232a01067.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-example-enhancing-order-execution-with-decorators">Example: Enhancing Order Execution with Decorators</h2>
<p>We have an <code>OrderExecutor</code> component responsible for executing trades. We want to add additional behaviors:</p>
<ul>
<li><p><strong>LoggingDecorator</strong>: Logs the details of each order execution.</p>
</li>
<li><p><strong>ValidationDecorator</strong>: Validates orders before execution.</p>
</li>
</ul>
<h3 id="heading-component-trait">Component Trait</h3>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Order</span></span> {
    symbol: <span class="hljs-built_in">String</span>,
    quantity: <span class="hljs-built_in">i32</span>,
    price: <span class="hljs-built_in">f64</span>,
}
<span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">OrderExecutor</span></span> {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">execute_order</span></span>(&amp;<span class="hljs-keyword">self</span>, order: &amp;Order) -&gt; <span class="hljs-built_in">Result</span>&lt;(), <span class="hljs-built_in">String</span>&gt;;
}
</code></pre>
<h3 id="heading-concrete-component">Concrete Component</h3>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">BasicOrderExecutor</span></span>;

<span class="hljs-keyword">impl</span> OrderExecutor <span class="hljs-keyword">for</span> BasicOrderExecutor {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">execute_order</span></span>(&amp;<span class="hljs-keyword">self</span>, order: &amp;Order) -&gt; <span class="hljs-built_in">Result</span>&lt;(), <span class="hljs-built_in">String</span>&gt; {
        <span class="hljs-comment">// Simulate order execution logic</span>
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Executing order: {:?}"</span>, order);
        <span class="hljs-literal">Ok</span>(())
    }
}
</code></pre>
<h3 id="heading-concrete-decorators">Concrete Decorators</h3>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">LoggingDecorator</span></span>&lt;T: OrderExecutor&gt; {
    execu
tor: T,
}

<span class="hljs-keyword">impl</span>&lt;T: OrderExecutor&gt; LoggingDecorator&lt;T&gt; {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>(executor: T) -&gt; <span class="hljs-keyword">Self</span> {
        LoggingDecorator { executor }
    }
}

<span class="hljs-keyword">impl</span>&lt;T: OrderExecutor&gt; OrderExecutor <span class="hljs-keyword">for</span> LoggingDecorator&lt;T&gt; {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">execute_order</span></span>(&amp;<span class="hljs-keyword">self</span>, order: &amp;Order) -&gt; <span class="hljs-built_in">Result</span>&lt;(), <span class="hljs-built_in">String</span>&gt; {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"LoggingDecorator: Order received: {:?}"</span>, order);
        <span class="hljs-keyword">let</span> result = <span class="hljs-keyword">self</span>.executor.execute_order(order);
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"LoggingDecorator: Order execution result: {:?}"</span>, result);
        result
    }
}
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">ValidationDecorator</span></span>&lt;T: OrderExecutor&gt; {
    executor: T,
}

<span class="hljs-keyword">impl</span>&lt;T: OrderExecutor&gt; ValidationDecorator&lt;T&gt; {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>(executor: T) -&gt; <span class="hljs-keyword">Self</span> {
        ValidationDecorator { executor }
    }
}

<span class="hljs-keyword">impl</span>&lt;T: OrderExecutor&gt; OrderExecutor <span class="hljs-keyword">for</span> ValidationDecorator&lt;T&gt; {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">execute_order</span></span>(&amp;<span class="hljs-keyword">self</span>, order: &amp;Order) -&gt; <span class="hljs-built_in">Result</span>&lt;(), <span class="hljs-built_in">String</span>&gt; {
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">self</span>.validate(order) {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Validated Order: {:?}"</span>, order);
            <span class="hljs-keyword">self</span>.executor.execute_order(order)
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-literal">Err</span>(<span class="hljs-built_in">String</span>::from(<span class="hljs-string">"Validation failed"</span>))
        }
    }
}

<span class="hljs-keyword">impl</span>&lt;T: OrderExecutor&gt; ValidationDecorator&lt;T&gt; {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">validate</span></span>(&amp;<span class="hljs-keyword">self</span>, order: &amp;Order) -&gt; <span class="hljs-built_in">bool</span> {
        <span class="hljs-comment">// Implement validation logic</span>
        order.quantity &gt; <span class="hljs-number">0</span> &amp;&amp; order.price &gt; <span class="hljs-number">0.0</span>
    }
}
</code></pre>
<h3 id="heading-client-code-1">Client Code</h3>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> order = Order {
        symbol: <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"AAPL"</span>),
        quantity: <span class="hljs-number">100</span>,
        price: <span class="hljs-number">150.0</span>,
    };

    <span class="hljs-comment">// Basic executor</span>
    <span class="hljs-keyword">let</span> basic_executor = BasicOrderExecutor;

    <span class="hljs-comment">// Decorate with validation</span>
    <span class="hljs-keyword">let</span> validated_executor = ValidationDecorator::new(basic_executor);

    <span class="hljs-comment">// Further decorate with logging</span>
    <span class="hljs-keyword">let</span> logged_executor = LoggingDecorator::new(validated_executor);

    <span class="hljs-comment">// Execute the order</span>
    <span class="hljs-keyword">let</span> result = logged_executor.execute_order(&amp;order);
    <span class="hljs-keyword">match</span> result {
        <span class="hljs-literal">Ok</span>(_) =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Order executed successfully."</span>),
        <span class="hljs-literal">Err</span>(e) =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Order execution failed: {}"</span>, e),
    }
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1729567874972/15085073-dfb2-43e3-b2ef-305ba436b051.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-notes-on-rust-implementation-1">Notes on Rust Implementation</h3>
<p>In this example, I used generics allowing static dispatch. By the way, in Rust, <strong>traits</strong> are not types themselves; they are a collection of methods that types can implement. You cannot instantiate a trait directly or store it as a field without using a pointer or a generic parameter. The following will result in compilation error because OrderExecutor is a trait.</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">ValidationDecorator</span></span> {
    executor: OrderExecutor,
}
</code></pre>
<p>In Rust, all types must have a known size at compile time unless they are behind a pointer (like <code>&amp;</code>, <code>Box</code>, or <code>Rc</code>) or used as a generic type parameter with trait bounds. By default, all generic type parameters and struct fields have an implicit <code>Sized</code> bound. This means that the compiler needs to know the size of the type at compile time.</p>
<p>The choice between generics and trait objects depends on your specific needs for performance and flexibility.</p>
<p>Instead of generics, you can use Trait Objects as follows:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">ValidationDecorator</span></span> {
    executor: <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> OrderExecutor&gt;,
}
</code></pre>
<p>This uses <strong>dynamic dispatch</strong>, which introduces a slight runtime overhead due to the use of a vtable.</p>
<h1 id="heading-factory-method-pattern">🏭Factory Method Pattern</h1>
<p><strong>Factory Method</strong> is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. This definition is by the <a target="_blank" href="https://refactoring.guru/design-patterns/factory-method">refactoring.guru</a>. The “<a target="_blank" href="https://read.amazon.com/kp/embed?asin=B08P3X99QP&amp;preview=newtab&amp;linkCode=kpe&amp;ref_=kip_embed_taf_preview_8ZBSPVJ7NA44QJKAFE9X">Head First Design Pattern</a>” more or less says the same:</p>
<blockquote>
<p>The Factory Method Patterns defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses.</p>
</blockquote>
<h2 id="heading-structure-3">Structure</h2>
<ul>
<li><p><strong>Product Interface</strong>: Defines the interface of objects the factory method creates.</p>
</li>
<li><p><strong>Concrete Products</strong>: Various implementations of the product interface.</p>
</li>
<li><p><strong>Creator (Factory)</strong>: Declares the factory method that returns new product objects.</p>
</li>
<li><p><strong>Concrete Creators</strong>: Override the factory method to change the resulting product's type.</p>
</li>
</ul>
<h2 id="heading-example-order-creation-factory">Example: Order Creation Factory</h2>
<p>Let's consider an example where we need to create different types of orders based on the current state of our trading strategy.</p>
<h3 id="heading-order-types">Order Types</h3>
<ul>
<li><p><strong>Market Order</strong>: Executes immediately at the current market price.</p>
</li>
<li><p><strong>Limit Order</strong>: Executes at a specified price or better.</p>
</li>
<li><p><strong>Stop Order</strong>: Becomes a market order when a specified price is reached.</p>
</li>
</ul>
<h3 id="heading-factory-method-uml-diagram">Factory Method UML Diagram</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731182181224/f55a74b7-41fc-4cd5-a8c2-9997ab93c0ce.png" alt class="image--center mx-auto" /></p>
<p>This is the class diagram structure we are implementing.</p>
<h3 id="heading-product-interface">Product Interface</h3>
<p>This interface is common to all the objects (in our case order types) that can be produced by the creator and its subclasses.</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Order</span></span> {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">place</span></span>(&amp;<span class="hljs-keyword">self</span>);
}
</code></pre>
<h3 id="heading-concrete-products">Concrete Products</h3>
<p><strong>Concrete Products</strong> are different implementations of the product interface. In our case different implementation of order types.</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">MarketOrder</span></span> {
    symbol: <span class="hljs-built_in">String</span>,
    quantity: <span class="hljs-built_in">u32</span>,
}

<span class="hljs-keyword">impl</span> Order <span class="hljs-keyword">for</span> MarketOrder {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">place</span></span>(&amp;<span class="hljs-keyword">self</span>) {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Placing Market Order: Buy {} units of {} at market price."</span>,
            <span class="hljs-keyword">self</span>.quantity, <span class="hljs-keyword">self</span>.symbol
        );
        <span class="hljs-comment">// Implement order placement logic here</span>
    }
}
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">LimitOrder</span></span> {
    symbol: <span class="hljs-built_in">String</span>,
    quantity: <span class="hljs-built_in">u32</span>,
    limit_price: <span class="hljs-built_in">f64</span>,
}

<span class="hljs-keyword">impl</span> Order <span class="hljs-keyword">for</span> LimitOrder {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">place</span></span>(&amp;<span class="hljs-keyword">self</span>) {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Placing Limit Order: Buy {} units of {} at ${}."</span>,
            <span class="hljs-keyword">self</span>.quantity, <span class="hljs-keyword">self</span>.symbol, <span class="hljs-keyword">self</span>.limit_price
        );
        <span class="hljs-comment">// Implement order placement logic here</span>
    }
}
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">StopOrder</span></span> {
    symbol: <span class="hljs-built_in">String</span>,
    quantity: <span class="hljs-built_in">u32</span>,
    stop_price: <span class="hljs-built_in">f64</span>,
}

<span class="hljs-keyword">impl</span> Order <span class="hljs-keyword">for</span> StopOrder {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">place</span></span>(&amp;<span class="hljs-keyword">self</span>) {
        <span class="hljs-built_in">println!</span>(
            <span class="hljs-string">"Placing Stop Order: Buy {} units of {} when price reaches ${}."</span>,
            <span class="hljs-keyword">self</span>.quantity, <span class="hljs-keyword">self</span>.symbol, <span class="hljs-keyword">self</span>.stop_price
        );
        <span class="hljs-comment">// Implement order placement logic here</span>
    }
}
</code></pre>
<h3 id="heading-creator-order-factory">Creator (Order Factory)</h3>
<p>It returns a different type of order.</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">OrderType</span></span> {
    Market,
    Limit(<span class="hljs-built_in">f64</span>), <span class="hljs-comment">// Limit price</span>
    Stop(<span class="hljs-built_in">f64</span>),  <span class="hljs-comment">// Stop price</span>
}
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">OrderFactory</span></span>;

<span class="hljs-keyword">impl</span> OrderFactory {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">create_order</span></span>(order_type: OrderType, symbol: <span class="hljs-built_in">String</span>, quantity: <span class="hljs-built_in">u32</span>) -&gt; <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> Order&gt; {
        <span class="hljs-keyword">match</span> order_type {
            OrderType::Market =&gt; <span class="hljs-built_in">Box</span>::new(MarketOrder { symbol, quantity }),
            OrderType::Limit(limit_price) =&gt; <span class="hljs-built_in">Box</span>::new(LimitOrder {
                symbol,
                quantity,
                limit_price,
            }),
            OrderType::Stop(stop_price) =&gt; <span class="hljs-built_in">Box</span>::new(StopOrder {
                symbol,
                quantity,
                stop_price,
            }),
        }
    }
}
</code></pre>
<h3 id="heading-client-code-2">Client Code</h3>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> symbol = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"AAPL"</span>);
    <span class="hljs-keyword">let</span> quantity = <span class="hljs-number">100</span>;
    <span class="hljs-comment">// Decide which order type to use</span>
    <span class="hljs-keyword">let</span> order_type = OrderType::Limit(<span class="hljs-number">149.0</span>);
    <span class="hljs-comment">// Create the order using the factory</span>
    <span class="hljs-keyword">let</span> order = OrderFactory::create_order(order_type, symbol.clone(), quantity);
    <span class="hljs-comment">// Place the order</span>
    order.place();
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730099717375/ed7dd1be-36fe-4cd6-8cef-e2550a1c7d3d.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-singleton-pattern"><strong>Singleton</strong> Pattern</h1>
<p><strong>Singleton</strong> is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance. Overall Singleton has almost the same pros and cons as global variables and generally a bad idea in context of concurrency.</p>
<p>In <strong>Rust</strong>, implementing singletons are pretty tricky due to its ownership model and emphasis on safe concurrency. It must solve these two problem:</p>
<ul>
<li><p><strong>Ensure a Class Has Only One Instance</strong>: Prevents multiple instances, guaranteeing that all clients use the same instance.</p>
</li>
<li><p><strong>Provide a Global Point of Access</strong>: Offers a way to access the single instance from anywhere in the application.</p>
</li>
</ul>
<p>Rust discourages global mutable state to prevent data races and ensure thread safety. And any global state must be safe to access from multiple threads. All these makes implementing singletons non-trivial. We can achieve this using different approach like using Mutex, static lifetime, OnceCell crate.</p>
<p>While a mutable singleton can be convenient, global mutable state can lead to code that's difficult to maintain and test. You always have option to pass the instance as a parameter to the parts of your code that needs it. As we are discussing singletons, lets implement using OnceCell.</p>
<h2 id="heading-oncecelllttgthttpscratesiocratesoncecell"><a target="_blank" href="https://crates.io/crates/once_cell">OnceCell&lt;T&gt;</a></h2>
<p>When you need to initialize data at runtime, possibly in a lazy manner, and ensure it is set only once. The core API looks <em>roughly</em> like</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span> OnceCell&lt;T&gt; {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>() -&gt; OnceCell&lt;T&gt; { ... }
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">set</span></span>(&amp;<span class="hljs-keyword">self</span>, value: T) -&gt; <span class="hljs-built_in">Result</span>&lt;(), T&gt; { ... }
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">Option</span>&lt;&amp;T&gt; { ... }
}
</code></pre>
<p>OnceCell has two varient <code>std::cell::OnceCell&lt;T&gt;</code> for single-threaded scenarios and <code>std::sync::OnceCell&lt;T&gt;</code> for thread-safe scenarios, can be shared between threads.</p>
<p><a target="_blank" href="https://github.com/matklad/once_cell">https://github.com/matklad/once_cell</a></p>
<p>However, since <code>OnceCell</code> provides immutable access to the initialized value, we need a way to mutate the instance after it's been set because singleton patterns allows mutable instance. To achieve a mutable singleton, we need combine <code>OnceCell</code> with interior mutability patterns. This involves wrapping the struct in types that allow mutation through immutable references, such as <code>RefCell</code> for single-threaded applications or <code>Mutex</code>/<code>RwLock</code> for multi-threaded applications.</p>
<h2 id="heading-example-trading-system-configmanager">Example: Trading System ConfigManager</h2>
<h3 id="heading-config">Config</h3>
<p>The <code>Config</code> struct holds various configuration settings. It derives <code>Deserialize</code> to allow loading from a JSON file.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> serde::Deserialize;

<span class="hljs-meta">#[derive(Debug, Deserialize)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Config</span></span> {
    <span class="hljs-keyword">pub</span> api_key: <span class="hljs-built_in">String</span>,
    <span class="hljs-keyword">pub</span> db_connection_string: <span class="hljs-built_in">String</span>,
    <span class="hljs-keyword">pub</span> trading_parameters: TradingParameters,
}

<span class="hljs-meta">#[derive(Debug, Deserialize)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">TradingParameters</span></span> {
    <span class="hljs-keyword">pub</span> max_positions: <span class="hljs-built_in">usize</span>,
    <span class="hljs-keyword">pub</span> risk_tolerance: <span class="hljs-built_in">f64</span>,
    <span class="hljs-comment">// Add other parameters as needed</span>
}
</code></pre>
<h3 id="heading-configmanager-singleton">ConfigManager Singleton</h3>
<p><code>OnceCell</code> ensures that the <code>ConfigManager</code> is initialized only once in a thread-safe manner. <code>instance</code> method provides global access to the singleton instance. The <code>new</code> method is private to prevent direct instantiation.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> once_cell::sync::OnceCell;
<span class="hljs-keyword">use</span> std::fs;

<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">ConfigManager</span></span> {
    config: Config,
}

<span class="hljs-keyword">impl</span> ConfigManager {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>() -&gt; <span class="hljs-keyword">Self</span> {
        <span class="hljs-keyword">let</span> config_data = fs::read_to_string(<span class="hljs-string">"config.json"</span>)
            .expect(<span class="hljs-string">"Failed to read configuration file"</span>);
        <span class="hljs-keyword">let</span> config: Config = serde_json::from_str(&amp;config_data)
            .expect(<span class="hljs-string">"Failed to parse configuration file"</span>);
        ConfigManager { config }
    }

    <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">instance</span></span>() -&gt; &amp;<span class="hljs-symbol">'static</span> ConfigManager {
        <span class="hljs-keyword">static</span> INSTANCE: OnceCell&lt;ConfigManager&gt; = OnceCell::new();
        INSTANCE.get_or_init(|| ConfigManager::new())
    }
    <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get_config</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; &amp;Config {
        &amp;<span class="hljs-keyword">self</span>.config
    }
}
</code></pre>
<h3 id="heading-use-configmanager">Use ConfigManager</h3>
<p>Now we can’t just use this TWAP that depends on a ConfigManager in some other context, without carrying over the ConfigManager to the other context, e.g. Unit Tests.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">OrderExecution</span></span> {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">execute</span></span>(&amp;<span class="hljs-keyword">self</span>);
}
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">TWAP</span></span>;

<span class="hljs-keyword">impl</span> OrderExecution <span class="hljs-keyword">for</span> TWAP {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">execute</span></span>(&amp;<span class="hljs-keyword">self</span>) {
        <span class="hljs-keyword">let</span> config_manager = ConfigManager::instance();
        <span class="hljs-keyword">let</span> max_positions = config_manager.get_config().trading_parameters.max_positions;
        <span class="hljs-keyword">let</span> risk_tolerance = config_manager.get_config().trading_parameters.risk_tolerance;
        <span class="hljs-comment">// Implement execution logic using the configurations</span>
    }
}
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> strategy = TWAP;
    strategy.execute();

    <span class="hljs-comment">// Access the ConfigManager directly elsewhere</span>
    <span class="hljs-keyword">let</span> api_key = ConfigManager::instance().get_config().api_key.clone();
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Using API Key: {}"</span>, api_key);
}
</code></pre>
<p>In this example, we can't change the <code>ConfigManager</code> instance. We've basically set up an immutable singleton (or a single Flyweight object).</p>
<p>To implement a mutable singleton <code>ConfigManager</code> struct using <code>OnceCell</code>, you need to wrap the ConfigManager in an Interior Mutability Type like using <code>RefCell&lt;ConfigManager&gt;</code> for single-threaded applications or using using <code>Mutex&lt;ConfigManager&gt;</code> or <code>RwLock&lt;ConfigManager&gt;</code> for multi-threaded applications. For example:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">static</span> CONFIG: OnceCell&lt;RefCell&lt;ConfigManager&gt;&gt; = OnceCell::new();
<span class="hljs-comment">//Multi-threaded</span>
<span class="hljs-keyword">static</span> CONFIG: OnceCell&lt;Mutex&lt;ConfigManager&gt;&gt; = OnceCell::new();
</code></pre>
<h2 id="heading-notes-on-rust">Notes on Rust</h2>
<h3 id="heading-what-is-mutexlttgt">What is Mutex&lt;T&gt;</h3>
<p>Mutex stands for mutual exclusion, which means it is used to protect shared data by allowing only one thread to access a resource or critical section at a time e.g. only exclusive borrows. Once a thread acquires a mutex, all other threads attempting to acquire the same mutex are blocked until the first thread releases the mutex.</p>
<p>The Rust standard library provides std::sync::Mutex&lt;T&gt;. It is generic over a type T, which is the type of the data the mutex is protecting. Its <code>lock()</code> method returns a special type called a <code>MutexGuard</code>. This guard represents the guarantee that we have locked the mutex. You unlock the mutex simply by dropping the guard.</p>
<p>Rust’s Mutex holds the data it’s protecting. In C++, on the other hand, std::mutex doesn’t hold the data it’s protecting and doesn’t even know what it’s protecting.</p>
<h3 id="heading-what-is-arcltmutexlttgtgt">What is Arc&lt;Mutex&lt;T&gt;&gt;</h3>
<p>Here, we want to share ownership of the data (<code>Mutex&lt;T&gt;</code>) between multiple threads. <code>Arc</code> provides shared ownership with thread-safe reference counting. <code>Arc&lt;Mutex&lt;T&gt;&gt;</code> allows multiple threads to own the same data and mutate it safely.</p>
<h1 id="heading-command-pattern">Command Pattern</h1>
<p><strong>Command</strong> is a behavioral design pattern that turns a request into a stand-alone object that contains all information about the request. This transformation lets you pass requests as a method arguments, delay or queue a request’s execution, and support undoable operations. This definition is by the <a target="_blank" href="https://refactoring.guru/design-patterns/factory-method">refactoring.guru</a>. The “<a target="_blank" href="https://read.amazon.com/kp/embed?asin=B08P3X99QP&amp;preview=newtab&amp;linkCode=kpe&amp;ref_=kip_embed_taf_preview_8ZBSPVJ7NA44QJKAFE9X">Head First Design Pattern</a>” says:</p>
<blockquote>
<p>The command pattern encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests and support undoable operations.</p>
</blockquote>
<p>Let consider an example where we have a <code>Portfolio</code> that keeps track of stock positions and cash balance. We support actions like <code>Add</code>, <code>Remove</code>, or <code>Reduce</code> positions, as well as <code>Deposit</code> and <code>Withdraw</code> funds to our portfolio. Lets make it more interesting and take a step forward and consider multiple treading scenario as one tread could be buying SPY, another selling MSFT and another thread depositing funds. We need to share <code>Portfolio</code> with different threads and it handles different commends.</p>
<h2 id="heading-structure-4">Structure</h2>
<ul>
<li><p><strong>Command interface</strong>: The <strong>Command</strong> interface usually methods for executing the command. We can defines <code>execute</code> and <code>rollback</code> methods with thread safety in mind.</p>
</li>
<li><p><strong>Receiver</strong>: The <strong>receiver</strong> class contains the business logic. Most commands only handle the details of how a request is passed to the receiver, while the receiver itself does the actual work. In our case the <code>Portfolio</code> is a receiver that stores positions and balance, protected by <code>Mutex</code> for safe concurrent access.</p>
</li>
<li><p><strong>Concrete Commands</strong>: Implement the <code>Command</code> trait for specific actions. A concrete command isn’t supposed to perform the work on its own, but rather to pass to the receiver. In our case we will implement add position and add funds commends.</p>
</li>
<li><p><strong>Invoker</strong>: The <strong>Invoker</strong> class is responsible for initiating requests. In our example we define a <code>Broker</code> that executes commands and maintains a history.</p>
</li>
<li><p><strong>Client</strong>: The application that creates commands and interacts with the broker.</p>
</li>
</ul>
<h3 id="heading-command-trait">Command Trait</h3>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::error::Error;
<span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">Command</span></span>: <span class="hljs-built_in">Send</span> + <span class="hljs-symbol">'static</span> {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">execute</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">Result</span>&lt;(), <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> Error&gt;&gt;;
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">rollback</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">Result</span>&lt;(), <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> Error&gt;&gt;;
}
</code></pre>
<p><code>Send</code> Trait ensures commands can be transferred across threads. The <code>Box&lt;dyn Error&gt;</code> is for flexible error types.</p>
<h3 id="heading-receiver-portfolio">Receiver: Portfolio</h3>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::collections::HashMap;
<span class="hljs-keyword">use</span> std::sync::{Arc, Mutex};
<span class="hljs-meta">#[derive(Clone)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Portfolio</span></span> {
    positions: Arc&lt;Mutex&lt;HashMap&lt;<span class="hljs-built_in">String</span>, <span class="hljs-built_in">i32</span>&gt;&gt;&gt;, <span class="hljs-comment">// symbol -&gt; quantity</span>
    balance: Arc&lt;Mutex&lt;<span class="hljs-built_in">f64</span>&gt;&gt;,                    <span class="hljs-comment">// cash balance</span>
}
<span class="hljs-keyword">impl</span> Portfolio {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>() -&gt; <span class="hljs-keyword">Self</span> {
        Portfolio {
            positions: Arc::new(Mutex::new(HashMap::new())),
            balance: Arc::new(Mutex::new(<span class="hljs-number">0.0</span>)),
        }
    }
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">add_position</span></span>(&amp;<span class="hljs-keyword">self</span>, symbol: &amp;<span class="hljs-built_in">str</span>, quantity: <span class="hljs-built_in">i32</span>) -&gt; <span class="hljs-built_in">Result</span>&lt;(), <span class="hljs-built_in">String</span>&gt; {
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> positions = <span class="hljs-keyword">self</span>.positions.lock().unwrap();
        <span class="hljs-keyword">let</span> entry = positions.entry(symbol.to_string()).or_insert(<span class="hljs-number">0</span>);
        *entry += quantity;
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Added {} shares of {}"</span>, quantity, symbol);
        <span class="hljs-literal">Ok</span>(())
    }
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">reduce_position</span></span>(...){...} <span class="hljs-comment">//Similar</span>
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">deposit</span></span>(&amp;<span class="hljs-keyword">self</span>, amount: <span class="hljs-built_in">f64</span>) -&gt; <span class="hljs-built_in">Result</span>&lt;(), <span class="hljs-built_in">String</span>&gt; {
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> balance = <span class="hljs-keyword">self</span>.balance.lock().unwrap();
        *balance += amount;
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Deposited ${}"</span>, amount);
        <span class="hljs-literal">Ok</span>(())
    }
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">withdraw</span></span>(...){...} <span class="hljs-comment">//Similar to deposit</span>
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get_balance</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">f64</span> {
        <span class="hljs-keyword">let</span> balance = <span class="hljs-keyword">self</span>.balance.lock().unwrap();
        *balance
    }

    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get_positions</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; HashMap&lt;<span class="hljs-built_in">String</span>, <span class="hljs-built_in">i32</span>&gt; {
        <span class="hljs-keyword">let</span> positions = <span class="hljs-keyword">self</span>.positions.lock().unwrap();
        positions.clone()
    }
}
</code></pre>
<p>We used <code>Arc&lt;Mutex&lt;HashMap&lt;String, i32&gt;&gt;&gt;</code> to allow shared mutable access across threads for position.</p>
<h3 id="heading-concrete-commands">Concrete Commands</h3>
<p>We implement two concreate commands <code>AddPositionCommand</code> and <code>WithdrawCommand</code>. Both command interacts with the <code>Portfolio</code> in a thread-safe manner and implements rollback functionality.</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">AddPositionCommand</span></span> {
    receiver: Arc&lt;Portfolio&gt;,
    symbol: <span class="hljs-built_in">String</span>,
    quantity: <span class="hljs-built_in">i32</span>,
}
<span class="hljs-keyword">impl</span> Command <span class="hljs-keyword">for</span> AddPositionCommand {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">execute</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">Result</span>&lt;(), <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> Error&gt;&gt; {
        <span class="hljs-keyword">self</span>.receiver.add_position(&amp;<span class="hljs-keyword">self</span>.symbol, <span class="hljs-keyword">self</span>.quantity)?;
        <span class="hljs-literal">Ok</span>(())
    }
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">rollback</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">Result</span>&lt;(), <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> Error&gt;&gt; {
        <span class="hljs-keyword">self</span>.receiver.reduce_position(&amp;<span class="hljs-keyword">self</span>.symbol, <span class="hljs-keyword">self</span>.quantity)?;
        <span class="hljs-literal">Ok</span>(())
    }
}
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">WithdrawCommand</span></span> {
    receiver: Arc&lt;Portfolio&gt;,
    amount: <span class="hljs-built_in">f64</span>,
}
<span class="hljs-keyword">impl</span> Command <span class="hljs-keyword">for</span> WithdrawCommand {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">execute</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">Result</span>&lt;(), <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> Error&gt;&gt; {
        <span class="hljs-keyword">self</span>.receiver.withdraw(<span class="hljs-keyword">self</span>.amount)?;
        <span class="hljs-literal">Ok</span>(())
    }
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">rollback</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">Result</span>&lt;(), <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> Error&gt;&gt; {
        <span class="hljs-keyword">self</span>.receiver.deposit(<span class="hljs-keyword">self</span>.amount)?;
        <span class="hljs-literal">Ok</span>(())
    }
}
</code></pre>
<h3 id="heading-invoker-broker">Invoker: Broker</h3>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Broker</span></span> {
    history: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> Command&gt;&gt;,
}
<span class="hljs-keyword">impl</span> Broker {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>() -&gt; <span class="hljs-keyword">Self</span> {
        Broker {
         history: <span class="hljs-built_in">Vec</span>::new(),
        }
    }
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">execute_command</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, <span class="hljs-keyword">mut</span> command: <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> Command&gt;) -&gt; <span class="hljs-built_in">Result</span>&lt;(), <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> Error&gt;&gt; {
        command.execute()?;
        <span class="hljs-keyword">self</span>.history.push(command);
        <span class="hljs-literal">Ok</span>(())
    }
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">rollback_last</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">Result</span>&lt;(), <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> Error&gt;&gt; {
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Some</span>(<span class="hljs-keyword">mut</span> command) = <span class="hljs-keyword">self</span>.history.pop() {
            command.rollback()?;
            <span class="hljs-literal">Ok</span>(())
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-literal">Err</span>(<span class="hljs-string">"No commands to rollback."</span>.into())
        }
    }
}
</code></pre>
<h3 id="heading-client-code-3">Client Code</h3>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() -&gt; <span class="hljs-built_in">Result</span>&lt;(), <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> std::error::Error&gt;&gt; {
    <span class="hljs-keyword">let</span> portfolio = Arc::new(Portfolio::new());
    <span class="hljs-keyword">let</span> broker = Arc::new(Mutex::new(Broker::new()));

    <span class="hljs-keyword">let</span> portfolio_clone1 = Arc::clone(&amp;portfolio);
    <span class="hljs-keyword">let</span> broker_clone1 = Arc::clone(&amp;broker);
    <span class="hljs-comment">// Add position</span>
    <span class="hljs-keyword">let</span> add_position_command = AddPositionCommand {
        receiver: portfolio.clone(),
        symbol: <span class="hljs-string">"AAPL"</span>.to_string(),
        quantity: <span class="hljs-number">50</span>,
    };
    <span class="hljs-keyword">let</span> deposit_handle = thread::spawn(<span class="hljs-keyword">move</span> || {
        <span class="hljs-keyword">let</span> deposit_command = DepositCommand {
            receiver: portfolio_clone1,
            amount: <span class="hljs-number">10000.0</span>,
        };
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> broker1 = broker_clone1.lock().unwrap();
        broker1.execute_command(<span class="hljs-built_in">Box</span>::new(deposit_command)).unwrap();
        <span class="hljs-built_in">drop</span>(broker1);
    });
    <span class="hljs-keyword">let</span> broker_clone2 = Arc::clone(&amp;broker);
    {
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> broker2 = broker_clone2.lock().unwrap();
        broker2.execute_command(<span class="hljs-built_in">Box</span>::new(add_position_command))?;
    }

    deposit_handle.join().unwrap();
    <span class="hljs-comment">// Print current portfolio state</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Current balance: ${}"</span>, portfolio.get_balance());
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Current positions: {:?}"</span>, portfolio.get_positions());
    <span class="hljs-comment">// Rollback last command (Withdraw)</span>
    {
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> broker3 = broker.lock().unwrap();
        broker3.rollback_last()?;
    }
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"\nAfter rollback of last command:"</span>);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Current balance: ${}"</span>, portfolio.get_balance());
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Current positions: {:?}"</span>, portfolio.get_positions());
    <span class="hljs-literal">Ok</span>(())
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1730665423685/44d1b519-244b-4e74-ba16-bca4dc3bdaab.png" alt class="image--center mx-auto" /></p>
<p>Here, I used <code>Arc&lt;Mutex&lt;Broker&gt;&gt;</code> to let multiple threads share access to the broker, ensuring the <code>execute_command</code> method is synchronized. While this isn't the perfect example since locking <code>Broker</code> might slow things down, it gives you a taste of multithreading and the command pattern.</p>
<p>As Broker might be doing tons of other operation we should at least minimize locking and lock only <code>history</code> to prevent contention and improve performance.</p>
<p>So, let's take out the <code>Mutex</code> around the <code>Broker</code> and redesign the broker as:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Broker</span></span> {
    history: Arc&lt;Mutex&lt;<span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> Command&gt;&gt;&gt;&gt;,
}
</code></pre>
<p>Now, the <code>history</code> is an <code>Arc&lt;Mutex&lt;Vec&lt;Box&lt;dyn Command&gt;&gt;&gt;&gt;</code>, which lets multiple parts of the program access the <code>Broker</code> at the same time while keeping the <code>history</code> synchronized.</p>
<h1 id="heading-the-ring-buffer-pattern">The ring buffer pattern</h1>
<p>The ring buffer pattern is not listed as a design pattern in the GoF book. It is more of a <strong>data structure</strong> or <strong>Producer-Consumer</strong> pattern than a design pattern. However, it is relevant in trading systems and fundamental for other pattern to understand. Let's dive in. Challenges Ahead!</p>
<p>The ring buffer as name suggest offers a fixed-size buffer that replaces old data when it fills up, making it perfect for processing data streams without interruption. It operates as a circular queue data structure, maintaining a first-in, first-out (FIFO) behavior, guided by two indices: one for reading and another for writing. So far so good.</p>
<h2 id="heading-what-is-a-ring-buffer">🔗What Is a Ring Buffer?</h2>
<p>A <strong>ring buffer</strong> is a fixed-size data structure that uses a single, contiguous block of memory in a circular fashion. When the write pointer reaches the end of the buffer, it wraps around to the beginning, overwriting the oldest data. Since it's a fixed-size buffer, it doesn't require dynamic memory allocation, and reading/writing operations are generally constant time, <code>O(1)</code>, making it highly desirable for low latency.</p>
<p>It has two pointers:</p>
<ul>
<li><p><strong>Head (Write Pointer)</strong>: Indicates where the next data element will be written.</p>
</li>
<li><p><strong>Tail (Read Pointer)</strong>: Indicates where the next data element will be read.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731197037821/20e9ae72-8268-4a7f-9714-9cfa56661d21.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<h3 id="heading-define-the-ring-buffer-struct">Define the Ring Buffer Struct</h3>
<p>We have learned the multithreading and Mutex in previous section. We can assume there will be two thread one for consumer and one for producer. As in the previous section we can use Mutex to lock head and tail and we should be good. However in this example we will do <strong><em>Lock-Free Ring Buffer Implementation</em></strong> for a Single Producer and Single Consumer. In general you almost never need to do the lock-free implementation (warning: stay away from Atomic), and your life is much better to just use locks. But we will do anyway, otherwise, how would we learn the Atomic and memory ordering. This is going to be mind blowing.</p>
<p>Lets define the <code>RingBuffer</code> struct.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">RingBuffer</span></span>&lt;T&gt; {
    buffer: <span class="hljs-built_in">Vec</span>&lt;UnsafeCell&lt;MaybeUninit&lt;T&gt;&gt;&gt;,
    capacity: <span class="hljs-built_in">usize</span>,
    head: AtomicUsize, <span class="hljs-comment">// Index for the producer</span>
    tail: AtomicUsize, <span class="hljs-comment">// Index for the consumer</span>
}
</code></pre>
<p>In this example, we're diving into the unsafe part, which means we're turning off some of the compiler's safety features. First, let's revisit some Rust concepts together.</p>
<h3 id="heading-what-is-celllttgt">What is Cell&lt;T&gt;?</h3>
<p><code>Cell&lt;T&gt;</code> is a type in Rust's standard library that provides <strong>interior mutability</strong> for values that implement the <code>Copy</code> trait. It allows you to get and set the value inside the <code>Cell&lt;T&gt;</code> even when you have only an immutable reference to it. This is particularly useful when you need to mutate data within a struct that is otherwise immutable.</p>
<p>There are scenarios where you need to mutate data even though you have only an immutable reference to it. This pattern is known as <strong>interior mutability</strong>. <code>Cell&lt;T&gt;</code> enables interior mutability by encapsulating the value and providing methods to access and modify it without requiring a mutable reference to the <code>Cell&lt;T&gt;</code> itself. Internally, it uses <code>UnsafeCell&lt;T&gt;</code> to bypass Rust's usual borrowing rules safely.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::cell::Cell;
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> cell = Cell::new(<span class="hljs-number">10</span>);
    <span class="hljs-comment">// Even though `cell` is immutable, we can get and set its value.</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Initial value: {}"</span>, cell.get());
    cell.set(<span class="hljs-number">20</span>);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Updated value: {}"</span>, cell.get());
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731226109905/6a03e421-bc61-4bc3-9c4e-e09577b19e94.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-what-is-unsafecelllttgthttpsdocrust-langorgstdcellstructunsafecellhtml">What is <a target="_blank" href="https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html">UnsafeCell&lt;T&gt;</a>?</h3>
<p><code>UnsafeCell&lt;T&gt;</code> is a type that wraps some <code>T</code> and indicates unsafe interior operations on the wrapped type. Types like <code>Cell&lt;T&gt;</code> and <code>RefCell&lt;T&gt;</code> in Rust's standard library are built upon <code>UnsafeCell&lt;T&gt;</code>. The <code>UnsafeCell</code> API <a target="_blank" href="https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html#method.get"><code>.get()</code></a> <a target="_blank" href="https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html#method.get">gives</a> you a raw pointer <code>*mut T</code> to its contents. It is up to <em>you</em> to use that raw pointer correctly.</p>
<p>Let's create our own cell!</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::cell::UnsafeCell;
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">MyCell</span></span>&lt;T&gt; {
    value: UnsafeCell&lt;T&gt;,
}
<span class="hljs-keyword">impl</span>&lt;T&gt; MyCell&lt;T&gt; {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>(value: T) -&gt; MyCell&lt;T&gt; {
        MyCell {
            value: UnsafeCell::new(value),
        }
    }
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; &amp;T {
        <span class="hljs-keyword">unsafe</span> { &amp;*<span class="hljs-keyword">self</span>.value.get() }
    }
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">set</span></span>(&amp;<span class="hljs-keyword">self</span>, new_value: T) {
        <span class="hljs-keyword">unsafe</span> {
            *<span class="hljs-keyword">self</span>.value.get() = new_value;
        }
    }
}
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> cell = MyCell::new(<span class="hljs-number">42</span>);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Cell value: {}"</span>, cell.get());
    cell.set(<span class="hljs-number">24</span>);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Cell value: {}"</span>, cell.get());
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731227097096/f4874003-cb49-457c-9eca-e687b45a2d71.png" alt class="image--center mx-auto" /></p>
<p>You have immutable cell with value 42 and and you can set to 24 without any problem.</p>
<p>Before we move to implementation, lets visit one more concepts <code>Send and Sync</code>.</p>
<h3 id="heading-implltt-sendgt-sync-for-structname">impl&lt;T: Send&gt; Sync for StructName {}</h3>
<p>In Rust, the <code>Send</code> and <code>Sync</code> traits are fundamental to the language's concurrency guarantees. They determine how types can be safely shared or transferred across threads when you see a line like</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span>&lt;T: <span class="hljs-built_in">Send</span>&gt; <span class="hljs-built_in">Sync</span> <span class="hljs-keyword">for</span> StructName&lt;T&gt; {}
</code></pre>
<p>It means that we're implementing the <code>Sync</code> trait for the type <code>StructName&lt;T&gt;</code>, where <code>T</code> is any type that implements <code>Send</code>. This implementation allows references to <code>StructName&lt;T&gt;</code> to be shared safely across multiple threads, provided that <code>T</code> is <code>Send</code>. A type <code>T</code> is <code>Send</code> if it is safe to transfer ownership of values of type <code>T</code> to another thread. A type <code>T</code> is <code>Sync</code> if it is safe to share references (<code>&amp;T</code>) to <code>T</code> between multiple threads.</p>
<p>Here we are asserting to the compiler that <code>StructName&lt;T&gt;</code> is <code>Sync</code> whenever <code>T</code> is <code>Send</code> and allow us to share the references to <code>StructName&lt;T&gt;</code> safely shared between threads.</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">StructName</span></span>&lt;T&gt; {
    data: T,
}
<span class="hljs-keyword">impl</span>&lt;T: <span class="hljs-built_in">Send</span>&gt; <span class="hljs-built_in">Sync</span> <span class="hljs-keyword">for</span> StructName&lt;T&gt; {}
</code></pre>
<p>When we compile this code, we see the error that says “An unsafe trait was implemented without an unsafe implementation.”</p>
<pre><code class="lang-yaml"><span class="hljs-string">error[E0200]:</span> <span class="hljs-string">the</span> <span class="hljs-string">trait</span> <span class="hljs-string">Sync</span> <span class="hljs-string">requires</span> <span class="hljs-string">an</span> <span class="hljs-string">unsafe</span> <span class="hljs-string">impl</span> <span class="hljs-string">declaration</span>
   <span class="hljs-string">|
27 | impl&lt;T: Send&gt; Sync for StructName&lt;T&gt; {}
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: the trait `Sync` enforces invariants that the compiler can't check.
 Review the trait documentation and make sure this implementation upholds those invariants before adding the `unsafe` keyword
help: add `unsafe` to this trait implementation
   |
27 | unsafe impl&lt;T: Send&gt; Sync for StructName&lt;T&gt; {}
   | ++++++</span>
</code></pre>
<p>As compiler cannot check its safety, we need to add <code>‘unsafe’</code> keyword. The <code>unsafe</code> keyword indicates that you are taking responsibility for ensuring that your implementation upholds the required safety guarantees.</p>
<h3 id="heading-what-is-maybeuninit">What is <code>MaybeUninit&lt;T&gt;</code>?</h3>
<p>A type that represents uninitialized memory. <code>MaybeUninit&lt;T&gt;</code> serves to enable unsafe code to deal with uninitialized data. It is a signal to the compiler indicating that the data here might <em>not</em> be initialized. Refer to below link for more details and examples.</p>
<p><a target="_blank" href="https://doc.rust-lang.org/std/mem/union.MaybeUninit.html">https://doc.rust-lang.org/std/mem/union.MaybeUninit.html</a></p>
<p>Overall <code>UnsafeCell</code> and <code>MaybeUninit</code> provide safer abstractions over raw pointers.</p>
<p><strong><em>assume_init_read(&amp;self) -&gt; T and assume_init_ref(&amp;self) -&gt; T</em></strong></p>
<p><strong><em>assume_init_read</em></strong> reads the value from the <code>MaybeUninit&lt;T&gt;</code> container. The resulting <code>T</code> is subject to the usual drop handling. This function creates a bitwise copy of the contents, regardless whether the contained type implements the <a target="_blank" href="https://doc.rust-lang.org/std/marker/trait.Copy.html"><code>Copy</code></a> t<a target="_blank" href="https://doc.rust-lang.org/std/marker/trait.Copy.html">rait</a> or not.</p>
<p><strong><em>assume_init_ref</em></strong> gets a shared reference to the contained value. This can be useful when we want to access a <code>MaybeUninit</code> that has been initialized but don’t have ownership of the <code>MaybeUninit</code> (preventing the use of <code>.assume_init()</code>).</p>
<h2 id="heading-ring-buffer-implementation">Ring Buffer Implementation</h2>
<pre><code class="lang-rust"><span class="hljs-keyword">unsafe</span> <span class="hljs-keyword">impl</span>&lt;T: <span class="hljs-built_in">Send</span>&gt; <span class="hljs-built_in">Sync</span> <span class="hljs-keyword">for</span> RingBuffer&lt;T&gt; {}
<span class="hljs-keyword">impl</span>&lt;T&gt; RingBuffer&lt;T&gt; {
    <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>(capacity: <span class="hljs-built_in">usize</span>) -&gt; <span class="hljs-keyword">Self</span> {
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> buffer = <span class="hljs-built_in">Vec</span>::with_capacity(capacity);
        <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..capacity {
            buffer.push(UnsafeCell::new(MaybeUninit::uninit()));
        }
        RingBuffer {
            buffer,
            capacity,
            head: AtomicUsize::new(<span class="hljs-number">0</span>),
            tail: AtomicUsize::new(<span class="hljs-number">0</span>),
        }
    }

    <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">push</span></span>(&amp;<span class="hljs-keyword">self</span>, item: T) -&gt; <span class="hljs-built_in">Result</span>&lt;(), T&gt; {
        <span class="hljs-keyword">let</span> head = <span class="hljs-keyword">self</span>.head.load(Ordering::Acquire);
        <span class="hljs-keyword">let</span> next_head = (head + <span class="hljs-number">1</span>) % <span class="hljs-keyword">self</span>.capacity;
        <span class="hljs-comment">// Check if buffer is full</span>
        <span class="hljs-keyword">if</span> next_head == <span class="hljs-keyword">self</span>.tail.load(Ordering::Acquire) {
            <span class="hljs-comment">// Buffer is full</span>
            <span class="hljs-keyword">return</span> <span class="hljs-literal">Err</span>(item);
        }
        <span class="hljs-keyword">unsafe</span> {
            <span class="hljs-keyword">let</span> cell = <span class="hljs-keyword">self</span>.buffer[head].get();
            (*cell).write(item);
        }
        <span class="hljs-keyword">self</span>.head.store(next_head, Ordering::Release);
        <span class="hljs-literal">Ok</span>(())
    }

    <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">pop</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">Option</span>&lt;T&gt; {
        <span class="hljs-keyword">let</span> tail = <span class="hljs-keyword">self</span>.tail.load(Ordering::Relaxed);

        <span class="hljs-keyword">if</span> tail == <span class="hljs-keyword">self</span>.head.load(Ordering::Acquire) {
            <span class="hljs-comment">// Buffer is empty</span>
            <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>;
        }
        <span class="hljs-keyword">let</span> item = <span class="hljs-keyword">unsafe</span> {
            <span class="hljs-keyword">let</span> cell = <span class="hljs-keyword">self</span>.buffer[tail].get();
            (*cell).assume_init_read()
        };
        <span class="hljs-keyword">let</span> next_tail = (tail + <span class="hljs-number">1</span>) % <span class="hljs-keyword">self</span>.capacity;
        <span class="hljs-keyword">self</span>.tail.store(next_tail, Ordering::Release);
        <span class="hljs-literal">Some</span>(item)
    }
}
<span class="hljs-keyword">impl</span>&lt;T&gt; <span class="hljs-built_in">Drop</span> <span class="hljs-keyword">for</span> RingBuffer&lt;T&gt; {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">drop</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>) {
        <span class="hljs-comment">// Clean up any initialized elements</span>
        <span class="hljs-keyword">let</span> head = <span class="hljs-keyword">self</span>.head.load(Ordering::Relaxed);
        <span class="hljs-keyword">let</span> tail = <span class="hljs-keyword">self</span>.tail.load(Ordering::Relaxed);

        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> idx = tail;
        <span class="hljs-keyword">while</span> idx != head {
            <span class="hljs-keyword">unsafe</span> {
                <span class="hljs-keyword">let</span> cell = <span class="hljs-keyword">self</span>.buffer[idx].get();
                (*cell).assume_init_drop();
            }
            idx = (idx + <span class="hljs-number">1</span>) % <span class="hljs-keyword">self</span>.capacity;
        }
    }
}
</code></pre>
<p>Let's go through this step by step. There's a lot to understand. We've already talked about <code>MaybeUninit&lt;T&gt;</code> and its methods, which are quite low-level. But what do <code>Ordering::Acquire</code> or <code>Ordering::Release</code> mean when we read and update head and tail? Memory ordering is the next concept we need to discuss.</p>
<h3 id="heading-memory-ordering">Memory Ordering</h3>
<p><strong>In simple terms, memory ordering</strong> refers to the sequence in which read and write operations on memory happen in a concurrent or multi-threaded environment. This order can vary because of optimizations like instruction reordering, caching, and the architecture's memory model.</p>
<p>Compilers and CPUs re-order your instructions to optimize the performance. We use AtomicUsize and its method e.g. <code>store</code>, <code>load</code>, <code>swap</code>, <code>compare_and_swap</code>, etc. These atomic operation is an indivisible operation that appears instantaneous to other threads. It ensures that no other thread can observe the operation in a partially completed state. When using atomic operations, we need to specify the <strong>memory ordering</strong>, which controls how operations are ordered with respect to other memory operations.</p>
<p>C<strong>ommon C++ Memory Orderings are</strong>:</p>
<ul>
<li><p><strong>Relaxed (</strong><code>memory_order_relaxed</code>): No ordering constraints; only atomicity is guaranteed.</p>
</li>
<li><p><strong>Acquire (</strong><code>memory_order_acquire</code>): Prevents memory reordering of subsequent reads/writes.</p>
</li>
<li><p><strong>Release (</strong><code>memory_order_release</code>): Prevents memory reordering of previous reads/writes.</p>
</li>
<li><p><strong>Acquire-Release</strong>: Combines acquire and release semantics.</p>
</li>
<li><p><strong>Sequentially Consistent (</strong><code>memory_order_seq_cst</code>): Provides a total ordering; all threads agree on the order of operations.</p>
</li>
</ul>
<p>Different CPU architectures have different memory models:</p>
<ul>
<li><p><strong>x86/x64 (Intel/AMD)</strong>: Generally strong memory ordering; most reads and writes are not reordered.</p>
</li>
<li><p><strong>ARM, PowerPC</strong>: Allow more reordering; require explicit memory barriers to enforce ordering.</p>
</li>
</ul>
<h3 id="heading-memory-ordering-in-rust">Memory Ordering in Rust</h3>
<p>Rust uses the same memory model as C++ for atomic operations. <strong>Memory Ordering</strong> is specified using <code>Ordering</code> enum. Ordering Variants in Rust</p>
<ul>
<li><p><code>Ordering::Relaxed</code></p>
</li>
<li><p><code>Ordering::Acquire</code></p>
</li>
<li><p><code>Ordering::Release</code></p>
</li>
<li><p><code>Ordering::AcqRel</code></p>
</li>
<li><p><code>Ordering::SeqCst</code></p>
</li>
</ul>
<p>This is a complicated topic, so for now, we'll just follow a few simple rules. We'll skip <code>Ordering::Relaxed</code> because it is quite weak. We can discuss it further later.</p>
<p>We apply <code>Ordering::Release</code> when <strong>writing</strong> to an atomic variable that will be read by other threads. It guarantees that all memory writes (<strong>before</strong> the release store) in the current thread become visible to other threads that perform an acquire load on the same atomic variable. In a way it says <em>"I'm releasing my changes so other threads can see them."</em></p>
<p>We apply <code>Ordering::Acquire</code> when <strong>reading</strong> from an atomic variable that was written by other threads. It guarantees that all memory reads and writes (<strong>after</strong> the acquire load) in the current thread see the effects of the writes that happened before the release store in another thread. In a way it says <em>"I'm acquiring the latest changes made by other threads."</em></p>
<p>Together, they ensure that memory operations are properly ordered and visible across threads, enabling safe and correct concurrent programming.</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(Debug,Clone)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">MarketDataTick</span></span> {
    <span class="hljs-keyword">pub</span> symbol: <span class="hljs-built_in">String</span>,
    <span class="hljs-keyword">pub</span> price: <span class="hljs-built_in">f64</span>,
    <span class="hljs-keyword">pub</span> volume: <span class="hljs-built_in">u32</span>,
    <span class="hljs-keyword">pub</span> timestamp: <span class="hljs-built_in">u32</span>,
}
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">start_producer</span></span>(buffer: Arc&lt;RingBuffer&lt;MarketDataTick&gt;&gt;) {
    thread::spawn(<span class="hljs-keyword">move</span> || {
        <span class="hljs-keyword">let</span> symbols = <span class="hljs-built_in">vec!</span>[<span class="hljs-string">"AAPL"</span>, <span class="hljs-string">"GOOG"</span>, <span class="hljs-string">"MSFT"</span>, <span class="hljs-string">"AMZN"</span>];
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> tick_count:<span class="hljs-built_in">u32</span> = <span class="hljs-number">0</span>;

        <span class="hljs-keyword">loop</span> {
            <span class="hljs-keyword">let</span> symbol = symbols[tick_count <span class="hljs-keyword">as</span> <span class="hljs-built_in">usize</span> % symbols.len()].to_string();
            <span class="hljs-keyword">let</span> tick = MarketDataTick {
                symbol,
                price: <span class="hljs-number">100.0</span> + tick_count <span class="hljs-keyword">as</span> <span class="hljs-built_in">f64</span>,
                volume: <span class="hljs-number">1000</span> + tick_count,
                timestamp: tick_count,
            };
            <span class="hljs-keyword">while</span> buffer.push(tick.clone()).is_err() {
                <span class="hljs-comment">// Buffer is full, handle accordingly</span>
                <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Buffer full, retrying..."</span>);
                thread::sleep(Duration::from_millis(<span class="hljs-number">1</span>));
            }
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Produced tick {}"</span>, tick_count);
            tick_count += <span class="hljs-number">1</span>;
            <span class="hljs-comment">// Simulate data arrival rate</span>
            thread::sleep(Duration::from_millis(<span class="hljs-number">10</span>));
        }
    });
}
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">start_consumer</span></span>(buffer: Arc&lt;RingBuffer&lt;MarketDataTick&gt;&gt;) {
    thread::spawn(<span class="hljs-keyword">move</span> || {
        <span class="hljs-keyword">loop</span> {
            <span class="hljs-keyword">match</span> buffer.pop() {
                <span class="hljs-literal">Some</span>(tick) =&gt; {
                    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Consumed tick: {:?}"</span>, tick);
                    <span class="hljs-comment">// Simulate processing time</span>
                    thread::sleep(Duration::from_millis(<span class="hljs-number">15</span>));
                }
                <span class="hljs-literal">None</span> =&gt; {
                    <span class="hljs-comment">// Buffer is empty, wait for new data</span>
                    thread::sleep(Duration::from_millis(<span class="hljs-number">1</span>));
                }
            }
        }
    });
}
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> buffer_capacity = <span class="hljs-number">100</span>;
    <span class="hljs-keyword">let</span> ring_buffer = Arc::new(RingBuffer::new(buffer_capacity));
    <span class="hljs-comment">// Start producer and consumer threads</span>
    start_producer(ring_buffer.clone());
    start_consumer(ring_buffer.clone());
    <span class="hljs-comment">// Let the simulation run for a while</span>
    thread::sleep(Duration::from_secs(<span class="hljs-number">5</span>));
}
</code></pre>
<h1 id="heading-state-pattern"><strong>State Pattern</strong></h1>
<p><strong>State</strong> is a behavioral design pattern that lets an object changes its behavior when its internal state changes. It's a pretty popular pattern from the Gang of Four 23 popular design patterns. I first learned this pattern from Head-First Design Pattern, so lets see what it says:</p>
<blockquote>
<p>The state pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.</p>
</blockquote>
<p>Imagine you have a trading system, and its behavior depends on its current state. Risk management is an essential part of any trading system, and you have integrated it into your system to enforce the right controls to adjust the system behavior based on current level of risk.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731788963869/1500e525-d696-4515-829a-e85bee0f41e2.png" alt class="image--center mx-auto" /></p>
<p>The state pattern can represent different risk states. Let’s consider an example where we have a "<strong>normal operation</strong>" state, where trading activities proceed as usual. If you take on a significant amount of risk and the VaR (Value at Risk) of your current position approaches the VaR limit (we'll discuss VaR later, but for now, remember that VaR measures risk in dollar terms), you enter a different state, let's call it the "Warning Level" state. This state limits your trading, increases monitoring, and sends email notifications about any additional positions. If you continue and exceed the VaR by a certain amount, it triggers another state, called the "Limit Breach" state. This state blocks new trades, may close existing positions, and allows for hedging. If you cannot close positions for some time and the situation worsens, it enters the "Shutdown Trading" state and starts shutdown procedures.</p>
<p>The benefits of using state pattern is that your system adapts to changing risk levels in real-time and changes its behavior. Risk policies, actions and controls are encapsulated within each state. The concepts and UML diagram of state pattern is similar to the strategy pattern.</p>
<h2 id="heading-key-concepts-of-the-state-pattern">Key Concepts of the State Pattern</h2>
<ul>
<li><p><strong>Context</strong>: The object that changes how it behaves based on its internal state. Context keeps a reference to one of the specific state objects and lets it handle all the work related to that state.</p>
</li>
<li><p><strong>State</strong>: An interface that defines the behavior associated with a particular state of the Context. The <strong>State</strong> interface declares the state-specific methods.</p>
</li>
<li><p><strong>Concrete States</strong>: Implementations of the State interface that define the behavior for each state.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731792233434/f7c154cc-7c40-4d5c-8018-7f84d837ae51.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<h2 id="heading-example-risk-management-system">Example: Risk Management system</h2>
<p>We'll model a risk management system that transitions through various states based on the Value at Risk (VaR) of the current trading positions. The states we'll implement are:</p>
<ul>
<li><p><strong>NormalOperationState</strong>: Trading proceeds as usual.</p>
</li>
<li><p><strong>WarningLevelState</strong>: Trading is limited, monitoring is increased, and notifications are sent.</p>
</li>
<li><p><strong>LimitBreachState</strong>: New trades are blocked, existing positions may be closed, and hedging is allowed.</p>
</li>
<li><p><strong>ShutdownState</strong>: Trading is halted, and shutdown procedures are initiated.</p>
</li>
</ul>
<h3 id="heading-define-a-state-riskstate-trait">Define a State: RiskState trait</h3>
<p>We'll define a <code>RiskState</code> trait that declares the methods each state must implement.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">RiskState</span></span>: fmt::<span class="hljs-built_in">Debug</span> {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">check_var</span></span>(&amp;<span class="hljs-keyword">self</span>, context: &amp;RiskManager) -&gt; <span class="hljs-built_in">Option</span>&lt;<span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> RiskState&gt;&gt;;
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">enter_state</span></span>(&amp;<span class="hljs-keyword">self</span>, context: &amp;RiskManager);
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">exit_state</span></span>(&amp;<span class="hljs-keyword">self</span>, context: &amp;RiskManager);
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">send_command</span></span>(&amp;<span class="hljs-keyword">self</span>, context: &amp;RiskManager);
}
</code></pre>
<p><code>check_var</code> method will be called to check the current VaR and decide if a state transition is needed. <code>enter_state</code> and <code>exit_state</code> methods can perform actions when entering or exiting a state (e.g., sending notifications, adjusting trading limits). <code>send_command</code> will be used to send commend to trading engine based on the state.</p>
<h3 id="heading-define-the-context-riskmanager">Define the Context": RiskManager</h3>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">RiskManager</span></span> {
    state: <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> RiskState&gt;,
    <span class="hljs-keyword">pub</span> var_limit: <span class="hljs-built_in">f64</span>,
    <span class="hljs-keyword">pub</span> warning_level: <span class="hljs-built_in">f64</span>,
    <span class="hljs-keyword">pub</span> current_var: <span class="hljs-built_in">f64</span>,
    <span class="hljs-keyword">pub</span> positions: HashMap&lt;<span class="hljs-built_in">String</span>, <span class="hljs-built_in">f64</span>&gt;, <span class="hljs-comment">// Position ID -&gt; VaR contribution</span>
    trading_engine_sender: Sender&lt;TradingEngineCommand&gt;,
}
</code></pre>
<p>The <code>RiskManager</code> struct will hold the current state, VaR limits, current VaR, and methods to update VaR and handle state transitions.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">TradingEngineCommand</span></span> {
    ExecuteTrade,
    NoTrade,
    StopEngine,
}
</code></pre>
<p><code>TradingEngineCommand</code> is the enum that we send as command to <code>TradingEngine</code> thread using <code>mpsc</code> channel.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">TradingEngine</span></span>;
<span class="hljs-keyword">impl</span> TradingEngine {
    <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">start</span></span>(receiver: mpsc::Receiver&lt;TradingEngineCommand&gt;) {
        thread::spawn(<span class="hljs-keyword">move</span> || {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Trading engine started."</span>);
            <span class="hljs-keyword">loop</span>{
                <span class="hljs-keyword">let</span> cmd = receiver.recv().unwrap();
                <span class="hljs-keyword">match</span> cmd {
                    TradingEngineCommand::ExecuteTrade =&gt; {
                        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Executing trade"</span>);
                    }
                    TradingEngineCommand::StopEngine =&gt; {
                        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Stopping trading engine."</span>);
                        <span class="hljs-comment">// Perform cleanup if necessary</span>
                        <span class="hljs-keyword">break</span>;}
                    TradingEngineCommand::NoTrade =&gt; {
                        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"No trade to execute."</span>);}
                }
            }
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Trading engine stopped."</span>);
        });
    }}
</code></pre>
<p>Let's implement the RiskManager. You can think of the RiskManager as being between the trading signals and the actual trading engine. The RiskManager receives the trade, checks its risk and state, and then sends a command to the trading engine to either trade, hold, or stop. Let's go through this step by step.</p>
<ul>
<li><p><code>update_var</code>: Recalculates the current VaR based on positions.</p>
</li>
<li><p><code>add_position</code> and <code>remove_position</code>: Modify positions and update VaR.</p>
</li>
<li><p><code>check_state</code>: Checks if a state transition is needed based on the current VaR.</p>
</li>
<li><p><code>change_state</code>: Handles the transition between states, calling <code>exit_state</code> on the old state and <code>enter_state</code> on the new state.</p>
</li>
<li><p><code>send_command</code>: Based on the state, it sends the command to the trading engine thread.</p>
</li>
</ul>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span> RiskManager {
    <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">new</span></span>(var_limit: <span class="hljs-built_in">f64</span>, warning_level: <span class="hljs-built_in">f64</span>, trading_engine_sender: Sender&lt;TradingEngineCommand&gt;) -&gt; <span class="hljs-keyword">Self</span> {
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> manager = RiskManager {
            state: <span class="hljs-built_in">Box</span>::new(NormalOperationState{cmd: TradingEngineCommand::ExecuteTrade}),
            var_limit,
            warning_level,
            current_var: <span class="hljs-number">0.0</span>,
            positions: HashMap::new(),
            trading_engine_sender,
        };
        manager
    }

    <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">update_var</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>) {
        <span class="hljs-keyword">self</span>.current_var = <span class="hljs-keyword">self</span>.positions.values().sum();
    }

    <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">add_position</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, position_id: &amp;<span class="hljs-built_in">str</span>, var_contribution: <span class="hljs-built_in">f64</span>) {
        <span class="hljs-keyword">self</span>.positions.insert(position_id.to_string(), var_contribution);
        <span class="hljs-keyword">self</span>.update_var();
        <span class="hljs-keyword">self</span>.check_state();
        <span class="hljs-keyword">self</span>.send_command();
    }

    <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">remove_position</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, position_id: &amp;<span class="hljs-built_in">str</span>) {
        <span class="hljs-keyword">self</span>.positions.remove(position_id);
        <span class="hljs-keyword">self</span>.update_var();
        <span class="hljs-keyword">self</span>.check_state();
        <span class="hljs-keyword">self</span>.send_command();
    }
    <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">send_command</span></span>(&amp;<span class="hljs-keyword">self</span>) {
        <span class="hljs-keyword">self</span>.state.send_command(&amp;<span class="hljs-keyword">self</span>);
    }
    <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">check_state</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>) {
        <span class="hljs-keyword">match</span> <span class="hljs-keyword">self</span>.state.check_var(<span class="hljs-keyword">self</span>){
            <span class="hljs-literal">Some</span>(state) =&gt; <span class="hljs-keyword">self</span>.change_state(state),
            <span class="hljs-literal">None</span> =&gt; (),
        }
    }

    <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">change_state</span></span>(&amp;<span class="hljs-keyword">mut</span> <span class="hljs-keyword">self</span>, new_state: <span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> RiskState&gt;) {
        <span class="hljs-keyword">self</span>.state.exit_state(<span class="hljs-keyword">self</span>);
        <span class="hljs-keyword">self</span>.state = new_state;
        <span class="hljs-keyword">self</span>.state.enter_state(<span class="hljs-keyword">self</span>);
    }

    <span class="hljs-keyword">pub</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">should_shutdown</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">bool</span> {
        <span class="hljs-keyword">self</span>.current_var &gt;= <span class="hljs-keyword">self</span>.var_limit * <span class="hljs-number">1.2</span>
    }
}
</code></pre>
<h3 id="heading-implement-concrete-states-normaloperationstate">Implement Concrete States: NormalOperationState</h3>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">NormalOperationState</span></span>{
    cmd: TradingEngineCommand
}

<span class="hljs-keyword">impl</span> RiskState <span class="hljs-keyword">for</span> NormalOperationState {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">check_var</span></span>(&amp;<span class="hljs-keyword">self</span>, context: &amp;RiskManager) -&gt; <span class="hljs-built_in">Option</span>&lt;<span class="hljs-built_in">Box</span>&lt;<span class="hljs-keyword">dyn</span> RiskState&gt;&gt; {
        <span class="hljs-keyword">if</span> context.current_var &gt;= context.warning_level &amp;&amp; context.current_var &lt; context.var_limit {
            <span class="hljs-literal">Some</span>(<span class="hljs-built_in">Box</span>::new(WarningLevelState{cmd: TradingEngineCommand::ExecuteTrade}))
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> context.current_var &gt;= context.var_limit {
            <span class="hljs-literal">Some</span>(<span class="hljs-built_in">Box</span>::new(LimitBreachState{cmd: TradingEngineCommand::NoTrade}))
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-literal">None</span>
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">enter_state</span></span>(&amp;<span class="hljs-keyword">self</span>, _context: &amp;RiskManager) {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Entering Normal Operation State"</span>);
        <span class="hljs-comment">// Reset limitations</span>
    }

    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">exit_state</span></span>(&amp;<span class="hljs-keyword">self</span>, _context: &amp;RiskManager) {
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Exiting Normal Operation State"</span>);
    }
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">send_command</span></span>(&amp;<span class="hljs-keyword">self</span>, context: &amp;RiskManager) {
        context.trading_engine_sender.send(<span class="hljs-keyword">self</span>.cmd.clone());
    }
}
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">send_email_notification</span></span>(message: &amp;<span class="hljs-built_in">str</span>) {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Sending email notification: {}"</span>, message);
}
</code></pre>
<p>The <code>WarningLevelState</code>, <code>LimitBreachState</code>, and <code>ShutdownState</code> work pretty much the same way, so we don't need to spell them out here.</p>
<h3 id="heading-client">Client</h3>
<p>Let's write a <code>main</code> function that simulates adding positions and triggering state transitions.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> var_limit = <span class="hljs-number">100.0</span>;
    <span class="hljs-keyword">let</span> warning_level = <span class="hljs-number">80.0</span>;
    <span class="hljs-keyword">let</span> (trading_engine_sender, trading_engine_receiver) = mpsc::channel();
    TradingEngine::start(trading_engine_receiver);

    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> risk_manager = RiskManager::new(var_limit, warning_level, trading_engine_sender);

    risk_manager.add_position(<span class="hljs-string">"Position1"</span>, <span class="hljs-number">30.0</span>);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Current VaR: {}"</span>, risk_manager.current_var);

    risk_manager.add_position(<span class="hljs-string">"Position2"</span>, <span class="hljs-number">40.0</span>);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Current VaR: {}"</span>, risk_manager.current_var);

    risk_manager.add_position(<span class="hljs-string">"Position3"</span>, <span class="hljs-number">20.0</span>);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Current VaR: {}"</span>, risk_manager.current_var);

    risk_manager.add_position(<span class="hljs-string">"Position4"</span>, <span class="hljs-number">15.0</span>);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Current VaR: {}"</span>, risk_manager.current_var);

    risk_manager.add_position(<span class="hljs-string">"Position5"</span>, <span class="hljs-number">35.0</span>);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Current VaR: {}"</span>, risk_manager.current_var);
    <span class="hljs-comment">// Simulate the passage of time and check if shutdown is needed</span>
    risk_manager.check_state();
    std::thread::sleep(std::time::Duration::from_secs(<span class="hljs-number">2</span>));
}
</code></pre>
<p>The <code>RiskManager</code> begins in the <code>NormalOperationState</code>. As you add positions and the <code>current_var</code> goes over the <code>warning_level</code>, it moves to the <code>WarningLevelState</code>. If the <code>current_var</code> goes beyond the <code>var_limit</code>, it shifts to the <code>LimitBreachState</code>. And if it surpasses 120% of the <code>var_limit</code>, it enters the <code>ShutdownState</code>. You can check out the full implementation here: <a target="_blank" href="https://github.com/siddharthqs/design-patterns-in-rust">https://github.com/siddharthqs/design-patterns-in-rust</a></p>
<p>The <code>RiskManager</code> interacts with the trading engine appropriately based on its current state, ensuring that state-specific jobs are performed correctly.</p>
<h1 id="heading-template-method-pattern">Template Method Pattern</h1>
<p>The <strong>Template Method Pattern</strong> is a behavioral design pattern that defines the skeleton of an algorithm in a method, deferring some steps to subclasses without changing the overall algorithm's structure. This pattern lets subclasses redefine certain steps of an algorithm without altering its structure.</p>
<p>This pattern is all about creating a template for an algorithm and allow subclasses to provide concreate implementation for some of the steps. It's like a blueprint for an algorithm that can be customized by subclasses. You can place your own custom logic in the template method and override the steps that need to be customized.</p>
<h2 id="heading-key-concepts">Key Concepts</h2>
<ul>
<li><p><strong>Abstract Class or Trait</strong>: Defines the template method and declares abstract methods representing steps that can vary.</p>
</li>
<li><p><strong>Template Method</strong>: A method that defines the skeleton of an algorithm, calling abstract methods that subclasses will implement.</p>
</li>
<li><p><strong>Concrete Subclasses</strong> : Provide implementations for the abstract methods, customizing the behavior of the algorithm.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1732388446362/2281f56e-f82b-412c-84c9-382173a424bf.png" alt class="image--center mx-auto" /></p>
<p>In Rust, the Template Method Pattern can be implemented using traits with default method implementations. This lets concrete types override specific behaviors. It's one of the most commonly used patterns!</p>
<p>In nearly every financial application, we use a Monte Carlo simulation framework, whether it's for pricing derivatives, managing risk, or generating simulations for backtesting. In this chapter, we'll implement the Monte Carlo Simulation using the template method pattern.</p>
<h2 id="heading-example-monte-carlo-simulation">Example: Monte Carlo Simulation</h2>
<p>In a nutshell, the concept of Monte Carlo simulation is pretty straightforward; it involves generating random numbers and averaging of the outcome.</p>
<p>We'll define a trait <code>MCSimulation</code> that provides default implementations for generating random numbers and a template method <code>simulation()</code>. The <code>simulation()</code> method first calls <code>generate_random_numbers()</code> and then calls <code>generate_path()</code>. The <code>generate_path()</code> function does not have an implementation in the trait and must be provided by concrete structs like <code>GeometricBrownianMotion</code>.</p>
<p>By using the Template Method Pattern, we can define the skeleton of the simulation algorithm while allowing subclasses to customize specific steps.</p>
<h3 id="heading-defining-the-mcsimulation-trait">Defining the <code>MCSimulation</code> Trait</h3>
<p>Let’s define the MCSimulation trait that includes a default implementation for generating standard normal random numbers, a template method simulation() and an abstract method that must be implemented by the structs that implement the trait.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">MCSimulation</span></span> {
    <span class="hljs-comment">/// Generates a vector of standard normal random numbers.</span>
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">generate_random_numbers</span></span>(&amp;<span class="hljs-keyword">self</span>, num: <span class="hljs-built_in">usize</span>) -&gt; <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">f64</span>&gt; {
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> rng = rand::thread_rng();
        (<span class="hljs-number">0</span>..num).map(|_| rng.sample(StandardNormal)).collect()
    }
    <span class="hljs-comment">/// Template method that runs the simulation.</span>
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">simulation</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">f64</span>&gt; {
        <span class="hljs-keyword">let</span> random_numbers = <span class="hljs-keyword">self</span>.generate_random_numbers(<span class="hljs-keyword">self</span>.get_number_of_steps());
        <span class="hljs-keyword">self</span>.generate_path(&amp;random_numbers)
    }
    <span class="hljs-comment">/// Abstract method to generate the path based on random numbers.</span>
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">generate_path</span></span>(&amp;<span class="hljs-keyword">self</span>, random_numbers: &amp;[<span class="hljs-built_in">f64</span>]) -&gt; <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">f64</span>&gt;;
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get_number_of_steps</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">usize</span>;
}
</code></pre>
<p><code>simulation()</code> is the template method that use <code>generate_path()</code>, an abstract method to be implemented by concrete structs, defining how to generate the simulation path.</p>
<h3 id="heading-implement-stochasticprocess-trait">Implement StochasticProcess Trait</h3>
<p>We define <code>StochasticProcess</code> trait for the underlying asset's stochastic process.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">trait</span> <span class="hljs-title">StochasticProcess</span></span> {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">drift</span></span>(&amp;<span class="hljs-keyword">self</span>, dt: <span class="hljs-built_in">f64</span>) -&gt; <span class="hljs-built_in">f64</span>;
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">diffusion</span></span>(&amp;<span class="hljs-keyword">self</span>, dt: <span class="hljs-built_in">f64</span>) -&gt; <span class="hljs-built_in">f64</span>;
}
</code></pre>
<h3 id="heading-geometric-brownian-motion">Geometric Brownian Motion</h3>
<p><code>GeometricBrownianMotion</code>implements <code>StochasticProcess</code></p>
<pre><code class="lang-rust"><span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">GeometricBrownianMotion</span></span> {
    <span class="hljs-keyword">pub</span> initial_value: <span class="hljs-built_in">f64</span>,
    <span class="hljs-keyword">pub</span> risk_free_rate: <span class="hljs-built_in">f64</span>,
    <span class="hljs-keyword">pub</span> volatility: <span class="hljs-built_in">f64</span>,
    <span class="hljs-keyword">pub</span> time_steps: <span class="hljs-built_in">usize</span>,
    <span class="hljs-keyword">pub</span> maturity: <span class="hljs-built_in">f64</span>,
}
<span class="hljs-keyword">impl</span> StochasticProcess <span class="hljs-keyword">for</span> GeometricBrownianMotion {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">drift</span></span>(&amp;<span class="hljs-keyword">self</span>, _dt: <span class="hljs-built_in">f64</span>) -&gt; <span class="hljs-built_in">f64</span> {
        (<span class="hljs-keyword">self</span>.risk_free_rate - <span class="hljs-number">0.5</span> * <span class="hljs-keyword">self</span>.volatility.powi(<span class="hljs-number">2</span>))* _dt
    }
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">diffusion</span></span>(&amp;<span class="hljs-keyword">self</span>, _dt: <span class="hljs-built_in">f64</span>) -&gt; <span class="hljs-built_in">f64</span> {
        <span class="hljs-keyword">self</span>.volatility * _dt.sqrt()
    }
}
</code></pre>
<h3 id="heading-implementing-mcsimulation">Implementing MCSimulation</h3>
<p>Now, let's have <code>GeometricBrownianMotion</code> implement the <code>MCSimulation</code> trait. It defines how to generate a path based on the Geometric Brownian Motion model.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span> MCSimulation <span class="hljs-keyword">for</span> GeometricBrownianMotion {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">get_number_of_steps</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">usize</span> {
        <span class="hljs-keyword">self</span>.time_steps
    }
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">generate_path</span></span>(&amp;<span class="hljs-keyword">self</span>, random_numbers: &amp;[<span class="hljs-built_in">f64</span>]) -&gt; <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">f64</span>&gt; {
        <span class="hljs-keyword">let</span> dt = <span class="hljs-keyword">self</span>.maturity / <span class="hljs-keyword">self</span>.time_steps <span class="hljs-keyword">as</span> <span class="hljs-built_in">f64</span>;
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> s = <span class="hljs-keyword">self</span>.initial_value;
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> path = <span class="hljs-built_in">Vec</span>::with_capacity(<span class="hljs-keyword">self</span>.time_steps + <span class="hljs-number">1</span>);
        path.push(s);
        <span class="hljs-keyword">for</span> &amp;dw <span class="hljs-keyword">in</span> random_numbers {
            <span class="hljs-keyword">let</span> drift = <span class="hljs-keyword">self</span>.drift(dt);
            <span class="hljs-keyword">let</span> diffusion = <span class="hljs-keyword">self</span>.diffusion(dt) * dw ;
            s = s * (drift + diffusion).exp();
            path.push(s);
        }
        path
    }
}
</code></pre>
<h3 id="heading-using-the-simulation-in-client-code">Using the Simulation in Client Code</h3>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> gbm = GeometricBrownianMotion {
        initial_value: <span class="hljs-number">100.0</span>,
        risk_free_rate: <span class="hljs-number">0.05</span>,
        volatility: <span class="hljs-number">0.2</span>,
        time_steps: <span class="hljs-number">1000</span>,
        maturity: <span class="hljs-number">1.0</span>,
    };
    <span class="hljs-keyword">let</span> path = gbm.simulation();
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Generated GBM path: {:?}"</span>, path);
}
</code></pre>
<p>We call the <code>simulation()</code> method, which generates a path using the Template Method Pattern.</p>
<p>By using the Template Method Pattern, we've created a flexible and extensible Monte Carlo simulation framework in Rust. The <code>MCSimulation</code> trait defines the overall simulation process, while concrete structs like <code>GeometricBrownianMotion</code> provide specific implementations for generating simulation paths. You can extend this framework to include other stochastic processes, such as the Heston model or the Cox-Ingersoll-Ross model, by implementing the <code>generate_path()</code> method accordingly.</p>
<h1 id="heading-limit-order-book-lob">Limit-Order Book (LOB)</h1>
<p>Todo!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731515256955/a2bf8616-6e69-4169-add2-b10043720005.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-conclusion"><strong>Conclusion</strong></h1>
<p>Design patterns like Strategy, Decorator, Observer, and Factory Method provide proven and adaptable solutions that help developers create strong and efficient trading systems. By learning and using these patterns, developers can greatly improve the quality, maintainability, and performance of algorithmic trading systems. By abstracting the creation of objects, by encapsulating execution and trading strategies separately, we can build systems that are easier to maintain, extend, and adapt to changing market conditions.</p>
<h1 id="heading-references">References</h1>
<p><a target="_blank" href="https://refactoring.guru/design-patterns/strategy">https://refactoring.guru/design-patterns/strategy</a></p>
<p><a target="_blank" href="https://rust-unofficial.github.io/patterns/patterns/index.html">https://rust-unofficial.github.io/patterns/patterns/index.html</a></p>
<p><a target="_blank" href="https://a.co/d/8yBCZcn">Rust Atomics and Locks-O'Reilly Media (2023)-Mara Bos</a></p>
<iframe sandbox="allow-scripts allow-same-origin allow-popups" width="336" height="550" style="max-width:100%" src="https://read.amazon.com/kp/card?asin=B08P3X99QP&amp;preview=inline&amp;linkCode=kpe&amp;ref_=kip_embed_taf_preview_8ZBSPVJ7NA44QJKAFE9X"></iframe>]]></content:encoded></item><item><title><![CDATA[Welcome to My Rough Rust Notes!]]></title><description><![CDATA[So, you’ve dipped your toes into Rust—perhaps by watching a few YouTube tutorials, reading a book, or experimenting with some code. But now, as you start coding, you find yourself constantly Googling or searching into StackOverflow for basic code. Th...]]></description><link>https://siddharthqs.com/welcome-to-my-rough-rust-cheat-sheet</link><guid isPermaLink="true">https://siddharthqs.com/welcome-to-my-rough-rust-cheat-sheet</guid><dc:creator><![CDATA[Siddharth]]></dc:creator><pubDate>Sun, 01 Sep 2024 04:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1726106840028/33066880-71d5-4945-8765-735662d1fcce.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>So, you’ve dipped your toes into Rust—perhaps by watching a few YouTube tutorials, reading a book, or experimenting with some code. But now, as you start coding, you find yourself constantly Googling or searching into StackOverflow for basic code. This ever-growing Rust cheat sheet is designed to save you time by compiling common code snippets for everyday Rust programming. Hopefully, it will save you time as well. Let's begin!</p>
<h1 id="heading-check-the-data-type-of-a-variable">Check the data type of a variable</h1>
<p>Rust provides a function <code>std::any::type_name::&lt;T&gt;()</code> that returns the name of the type as a string.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::any::type_name;
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">type_of</span></span>&lt;T&gt;(_: &amp;T) -&gt; &amp;<span class="hljs-symbol">'static</span> <span class="hljs-built_in">str</span> {
    type_name::&lt;T&gt;()
}
<span class="hljs-keyword">let</span> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"Hello, World!"</span>);
<span class="hljs-keyword">let</span> x = s.chars().nth(<span class="hljs-number">0</span>);
<span class="hljs-built_in">println!</span>(<span class="hljs-string">"x is of type: {}"</span>, type_of(&amp;x)); 
<span class="hljs-comment">//x is of type: core::option::Option&lt;char&gt;</span>
</code></pre>
<h1 id="heading-using-stdfmt">Using std::fmt</h1>
<p>The fmt module provides functionality for formatting and printing, including traits like Display and Debug which are used to control how types are formatted when printed. Let’s see a example:</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::fmt;
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Point</span></span> {
    x: <span class="hljs-built_in">i32</span>,
    y: <span class="hljs-built_in">i32</span>,
}
<span class="hljs-keyword">impl</span> fmt::Display <span class="hljs-keyword">for</span> Point {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">fmt</span></span>(&amp;<span class="hljs-keyword">self</span>, f: &amp;<span class="hljs-keyword">mut</span> fmt::Formatter) -&gt; fmt::<span class="hljs-built_in">Result</span> {
        <span class="hljs-built_in">write!</span>(f, <span class="hljs-string">"({}, {})"</span>, <span class="hljs-keyword">self</span>.x, <span class="hljs-keyword">self</span>.y)
    }
}
<span class="hljs-keyword">impl</span> fmt::<span class="hljs-built_in">Debug</span> <span class="hljs-keyword">for</span> Point {
    <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">fmt</span></span>(&amp;<span class="hljs-keyword">self</span>, f: &amp;<span class="hljs-keyword">mut</span> fmt::Formatter) -&gt; fmt::<span class="hljs-built_in">Result</span> {
        <span class="hljs-built_in">write!</span>(f, <span class="hljs-string">"Point {{ x: {}, y: {} }}"</span>, <span class="hljs-keyword">self</span>.x, <span class="hljs-keyword">self</span>.y)
    }
}
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> point = Point { x: <span class="hljs-number">1</span>, y: <span class="hljs-number">2</span> };
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Display: {}"</span>, point);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Debug: {:?}"</span>, point);
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1731793542324/03cf048f-c027-4e29-8945-c2684bf94a3e.png" alt class="image--center mx-auto" /></p>
<p><code>fmt::Formatter</code> contains the state necessary for formatting. It is passed as a mutable reference to the fmt method when implementing formatting traits like Display and Debug. It provides methods to write formatted data to the output. <code>fmt::Result</code> is an alias for Result&lt;(), std::fmt::Error&gt;. It is the return type for the fmt method, indicating whether the formatting operation was successful or if an error occurred.</p>
<h1 id="heading-minimum-and-maximum">Minimum and Maximum</h1>
<p>Use <strong>std::cmp::min(a,b) to</strong> compare two values a and b. This function works with any type that implements the Ord trait, such as integer, float and other comparable types. Similarly cmp::max() works.</p>
<p>For float-point numbers f32 or f64, you can use it’s function min.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> min  = std::cmp::min(a,b);
<span class="hljs-keyword">let</span> max  = std::cmp::max(a,b);

a.min(b);
a.max(b);
</code></pre>
<p>The cmp method in Rust returns an ordering result which can be Less, Equal or Greater.</p>
<pre><code class="lang-rust"><span class="hljs-comment">//Signature of cmp</span>
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">cmp</span></span>(&amp;<span class="hljs-keyword">self</span>, other: &amp;<span class="hljs-keyword">Self</span>) -&gt; Ordering
<span class="hljs-keyword">let</span> comparison = a.cmp(&amp;b);
<span class="hljs-keyword">match</span> comparison {
    std::cmp::Ordering::Less =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"a is less than b"</span>),
    std::cmp::Ordering::Equal =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"a is equal to b"</span>),
    std::cmp::Ordering::Greater =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"a is greater than b"</span>),
    }
</code></pre>
<h1 id="heading-vector">Vector</h1>
<p>A <code>Vec&lt;T&gt;</code> in Rust is a growable, heap-allocated, contiguous sequence of elements of type <code>T</code>.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> v: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt; = <span class="hljs-built_in">Vec</span>::new(); <span class="hljs-comment">//Empty Vector</span>
<span class="hljs-keyword">let</span> v = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]; <span class="hljs-comment">//Using the vec! Macro </span>
v.retain(|&amp;x| x % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>); <span class="hljs-comment">// Keeps only even numbers</span>
<span class="hljs-comment">//Remove all instances of a value in place </span>
v.retain(|&amp;x| x != val);

<span class="hljs-comment">//Iterating Over Vectors</span>
<span class="hljs-keyword">for</span> val <span class="hljs-keyword">in</span> &amp;v { <span class="hljs-comment">//Iterating by Reference</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, val);
}
<span class="hljs-keyword">for</span> val <span class="hljs-keyword">in</span> &amp;<span class="hljs-keyword">mut</span> v { <span class="hljs-comment">//Iterating by Mutable Reference</span>
    *val *= <span class="hljs-number">2</span>;
}
<span class="hljs-keyword">for</span> val <span class="hljs-keyword">in</span> v { <span class="hljs-comment">//Consuming the Vector</span>
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, val);
}
<span class="hljs-comment">// v cannot be used after this point</span>
<span class="hljs-keyword">let</span> v1 = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">let</span> v2 = v1; <span class="hljs-comment">// v1 is moved to v2</span>
<span class="hljs-comment">// v1 is no longer accessible</span>
<span class="hljs-comment">//Only one mutable reference or any number of immutable references.</span>
</code></pre>
<h2 id="heading-minimum-maximum-and-sum-of-a-vector">Minimum, Maximum and Sum of a Vector</h2>
<p>Use the <code>iter()</code> method combined with the <code>max()</code> and <code>min()</code> functions, <code>min()</code> and <code>max()</code> are methods from the <code>Iterator</code> trait that return <code>Option&lt;&amp;T&gt;</code>. The result will be <code>Some(value)</code> if the vector is non-empty, or <code>None</code> if the vector is empty. The values need to be unwrapped using pattern matching.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> v = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">80</span>, <span class="hljs-number">50</span>, <span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">45</span>, <span class="hljs-number">30</span>];
<span class="hljs-keyword">match</span> v.iter().min() {
    <span class="hljs-literal">Some</span>(min_value) =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Minimum value: {}"</span>, min_value),
    <span class="hljs-literal">None</span> =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"The vector is empty!"</span>),
}
<span class="hljs-comment">// Using let Some</span>
<span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Some</span>(max_value) = v.iter().max() {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Maximum value: {}"</span>, max_value);
}
<span class="hljs-comment">// Sum the elements using sum()</span>
<span class="hljs-keyword">let</span> total: <span class="hljs-built_in">i32</span> = v.iter().sum();
<span class="hljs-keyword">let</span> total: <span class="hljs-built_in">i32</span> = v.iter().fold(<span class="hljs-number">0</span>, |acc, &amp;x| acc + x);
</code></pre>
<h2 id="heading-slicing-of-vector">Slicing of Vector</h2>
<p>Let’s say you want to iterate over a vector starting from second element (i.e., excluding the first element):</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> v = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">80</span>, <span class="hljs-number">50</span>, <span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">45</span>, <span class="hljs-number">30</span>];
<span class="hljs-comment">//Using Slice of vector</span>
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> &amp;v[<span class="hljs-number">1</span>..] {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, i);
}

<span class="hljs-comment">//Using Mutable Slices for Modification</span>
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> &amp;<span class="hljs-keyword">mut</span> v[<span class="hljs-number">1</span>..] {
    *i += <span class="hljs-number">5</span>;  <span class="hljs-comment">// To modify each element dereference i with *i</span>
}

<span class="hljs-comment">//Using Index-Based Looping</span>
<span class="hljs-keyword">for</span> idx <span class="hljs-keyword">in</span> <span class="hljs-number">1</span>..v.len() {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Index: {}, Value: {}"</span>, idx, v[idx]);
}
<span class="hljs-comment">//Using Enumerate with Skip</span>
<span class="hljs-keyword">for</span> (idx, val) <span class="hljs-keyword">in</span> v.iter().enumerate().skip(<span class="hljs-number">1</span>) {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Index: {}, Value: {}"</span>, idx, val);
}
</code></pre>
<p><code>&amp;v[1..]</code> : This creates an immutable slice of <code>v</code> starting from index <code>1</code> to the end.</p>
<h2 id="heading-sorting">Sorting</h2>
<p>The <code>sort()</code> method sorts the elements of the vector <strong><em>in place</em></strong> in ascending order. The elements must implement the <code>Ord</code> trait.</p>
<p>If you want to sort with a custom comparator, you can use the <code>sort_by()</code> method, which takes a closure to determine the order of elements.</p>
<pre><code class="lang-rust">v.sort();  <span class="hljs-comment">// Sorts in ascending order</span>
v.sort_by(|a, b| b.cmp(a)); <span class="hljs-comment">// Sorting in descending order</span>
</code></pre>
<p>Let’s say you want to sort vector of vectors based on some conditions such as the first element of each inner vector, or sum of elements etc., you can use sort_by() method. Here are a few examples:</p>
<pre><code class="lang-rust"><span class="hljs-comment">// Sorts by the first element</span>
vec_of_vecs.sort_by(|a, b| a[<span class="hljs-number">0</span>].cmp(&amp;b[<span class="hljs-number">0</span>]));
<span class="hljs-comment">// Sorts by the length of inner vectors</span>
vec_of_vecs.sort_by(|a, b| a.len().cmp(&amp;b.len()));
<span class="hljs-comment">// Sorts by sum of elements</span>
vec_of_vecs.sort_by(|a, b| a.iter().sum::&lt;<span class="hljs-built_in">i32</span>&gt;().cmp(&amp;b.iter().sum::&lt;<span class="hljs-built_in">i32</span>&gt;()));
</code></pre>
<h1 id="heading-hashmap">HashMap</h1>
<p>The <code>HashMap</code> in Rust is a key-value store from the <code>std::collections</code> module. You can use the <code>get()</code> method, which returns an <code>Option</code>.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> m:HashMap&lt;<span class="hljs-built_in">i32</span>,<span class="hljs-built_in">i32</span>&gt; = HashMap::new(); <span class="hljs-comment">//Declaring a HashMap</span>
m.insert(<span class="hljs-number">1</span>,<span class="hljs-number">1</span>); <span class="hljs-comment">//Inserting Values into a HashMap</span>
m.insert(<span class="hljs-number">2</span>,<span class="hljs-number">2</span>);
<span class="hljs-keyword">let</span> n = <span class="hljs-number">2</span>;
<span class="hljs-comment">//Accessing Values from a HashMap using match</span>
<span class="hljs-keyword">match</span> m.get(&amp;n){
    <span class="hljs-literal">Some</span>(value) =&gt; {<span class="hljs-built_in">println!</span>(<span class="hljs-string">"Value for 'n': {}"</span>, *value);}
    <span class="hljs-literal">None</span> =&gt; { <span class="hljs-comment">//Key does not exist</span>
        <span class="hljs-keyword">let</span> value = <span class="hljs-number">2</span>;
        m.insert(n,value);
        }
    }
<span class="hljs-comment">//Accessing Values using if let</span>
<span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Some</span>(value) = m.get(<span class="hljs-number">2</span>) {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Value for 2: {}"</span>, value);
} <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Key not found"</span>);
}

<span class="hljs-comment">//Using contains_key</span>
<span class="hljs-keyword">if</span> m.contains_key(<span class="hljs-number">2</span>) {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Key exists"</span>);
} <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Key does not exist"</span>);
}
<span class="hljs-comment">// Removing Values from a HashMap</span>
<span class="hljs-keyword">let</span> removed_value = m.remove(<span class="hljs-number">2</span>);
<span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, removed_value);
</code></pre>
<h2 id="heading-find-the-key-with-the-maximum-value">Find the key with the maximum value</h2>
<p>You can use the <code>iter()</code> method to iterate over the key-value pairs and use the <code>max_by_key()</code> method to find the pair with the highest value.</p>
<pre><code class="lang-rust"><span class="hljs-comment">// Find the key with the maximum value</span>
<span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Some</span>((k, v)) = m.iter().max_by_key(|entry| entry.<span class="hljs-number">1</span>) {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"max key and maximum value is: {}: {}"</span>, k, v);
} <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"The HashMap is empty."</span>);
}
</code></pre>
<p><code>max_by_key(|entry| entry.1)</code> finds the key-value pair with the maximum value. Here, <code>entry</code> is a tuple <code>(&amp;key, &amp;value)</code>, and <code>entry.1</code> accesses the value.</p>
<h2 id="heading-entry">.entry()</h2>
<p>It returns an <code>Entry</code> enum, which represents either a vacant entry (<code>Vacant</code>) if the key is not present or an occupied entry (<code>Occupied</code>) if the key is already present. <code>or_insert(value)</code> inserts <code>value</code> into the map if the key is not already present and returns a mutable reference to the value in the map (either the existing one or the newly inserted one).</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> map = HashMap::new();
<span class="hljs-comment">// Access the entry for the key 'a'</span>
map.entry(<span class="hljs-string">'a'</span>).or_insert(<span class="hljs-number">0</span>);
<span class="hljs-comment">// Now the map contains {'a': 0}</span>
<span class="hljs-keyword">let</span> count = map.entry(<span class="hljs-string">'a'</span>).or_insert(<span class="hljs-number">0</span>);
*count += <span class="hljs-number">1</span>; <span class="hljs-comment">// Increment the count for 'a'</span>
</code></pre>
<h2 id="heading-getmut">.get_mut()</h2>
<p><code>get_mut()</code> retrieves a <strong>mutable reference</strong> to a value in a <code>HashMap</code>. It returns an <code>Option&lt;&amp;mut V&gt;</code>, so you can modify the value if the key exists (<code>Some(&amp;mut value)</code>).</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> m: HashMap&lt;<span class="hljs-built_in">i32</span>, <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt;&gt; = HashMap::new();    
<span class="hljs-comment">// Initialize the HashMap with empty vectors</span>
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..<span class="hljs-number">5</span> {
    m.insert(i, <span class="hljs-built_in">Vec</span>::new());
}
<span class="hljs-comment">//my_vec: Vec&lt;Vec&lt;i32&gt;&gt;</span>
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> &amp;my_vec {
    <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Some</span>(t) = m.get_mut(&amp;i[<span class="hljs-number">0</span>]) { <span class="hljs-comment">//get_mut() retrieves a mutable reference </span>
        t.push(i[<span class="hljs-number">1</span>]);
   }
}
</code></pre>
<h1 id="heading-binaryheap">BinaryHeap</h1>
<p><code>BinaryHeap</code> is a <strong>max-heap</strong>, meaning the largest element is always at the top.</p>
<p><strong>Heap Operations:</strong></p>
<ul>
<li><p><code>push(value)</code>: Inserts a value into the heap.</p>
</li>
<li><p><code>pop()</code>: Removes and returns the greatest value (for max-heap).</p>
</li>
<li><p><code>peek()</code>: Returns a reference to the greatest value without removing it.</p>
</li>
</ul>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> heap = BinaryHeap::new();
 <span class="hljs-comment">// Insert elements into the heap</span>
heap.push(<span class="hljs-number">5</span>);
<span class="hljs-keyword">let</span> vec = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">5</span>, <span class="hljs-number">1</span>, <span class="hljs-number">10</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">let</span> heap2 = BinaryHeap::from(vec); <span class="hljs-comment">//vec is no longer usable after this</span>
 <span class="hljs-comment">//Using collect with an Iterator</span>
<span class="hljs-keyword">let</span> heap3: BinaryHeap&lt;_&gt; = vec.into_iter().collect();
</code></pre>
<h2 id="heading-finding-the-kth-largest-element">Finding the Kth Largest Element</h2>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">find_kth_largest</span></span>(nums: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt;, k: <span class="hljs-built_in">usize</span>) -&gt; <span class="hljs-built_in">i32</span> {
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> heap = BinaryHeap::from(nums);
    <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..k - <span class="hljs-number">1</span> {
        heap.pop();
    }
    heap.pop().unwrap()
}
</code></pre>
<h1 id="heading-hashset">HashSet</h1>
<p>A <code>HashSet&lt;T&gt;</code> is an unordered collection of unique values of type <code>T</code>, implemented as a hash table.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> set: HashSet&lt;<span class="hljs-built_in">i32</span>&gt; = HashSet::new();
<span class="hljs-keyword">let</span> vec = <span class="hljs-built_in">vec!</span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
<span class="hljs-keyword">let</span> set: HashSet&lt;_&gt; = vec.into_iter().collect();
<span class="hljs-comment">//Using the From Trait</span>
<span class="hljs-keyword">let</span> set = HashSet::from([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]);

<span class="hljs-comment">//adding elements</span>
set.insert(<span class="hljs-number">77</span>);
<span class="hljs-comment">//Removing Elements</span>
set.remove(&amp;<span class="hljs-number">77</span>); <span class="hljs-comment">//Returns true if the element was present.</span>

<span class="hljs-comment">//Checking for Elements</span>
<span class="hljs-keyword">if</span> set.contains(&amp;<span class="hljs-number">77</span>) {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Set contains 77."</span>);
}
</code></pre>
<h2 id="heading-set-operations">Set Operations</h2>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> set_a = HashSet::from([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]);
<span class="hljs-keyword">let</span> set_b = HashSet::from([<span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]);
<span class="hljs-comment">//Returns an iterator</span>
<span class="hljs-keyword">let</span> <span class="hljs-class"><span class="hljs-keyword">union</span>: <span class="hljs-title">HashSet</span></span>&lt;_&gt; = set_a.union(&amp;set_b).cloned().collect();
<span class="hljs-keyword">let</span> intersection: HashSet&lt;_&gt; = set_a.intersection(&amp;set_b).cloned().collect();
<span class="hljs-keyword">let</span> difference: HashSet&lt;_&gt; = set_a.difference(&amp;set_b).cloned().collect();
<span class="hljs-comment">//Returns an iterator over elements that are in either set_a or set_b but not in both.</span>
<span class="hljs-keyword">let</span> sym_diff: HashSet&lt;_&gt; = set_a.symmetric_difference(&amp;set_b).cloned().collect();

<span class="hljs-comment">//Subset and Superset Checks</span>
<span class="hljs-keyword">if</span> set_a.is_subset(&amp;set_b) {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"set_a is a subset of set_b"</span>);
}
<span class="hljs-keyword">if</span> set_a.is_superset(&amp;set_b) {
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"set_a is a superset of set_b"</span>);
}
</code></pre>
<h2 id="heading-convert-a-hashset-to-a-vec">Convert a <code>HashSet</code> to a <code>Vec</code></h2>
<p>A <code>HashSet</code> is unordered, so when you collect its elements into a <code>Vec</code>, the order in the resulting vector is arbitrary. This is straightforward using the <code>iter()</code> method and the <code>collect()</code> function.</p>
<p><code>.cloned()</code> creates an iterator that yields owned copies of the elements.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> vec: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt; = hash_set.iter().cloned().collect();
<span class="hljs-comment">//Using into_iter() </span>
<span class="hljs-comment">//This moves the elements out of the HashSet and into the vector.</span>
<span class="hljs-keyword">let</span> vec: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt; = hash_set.into_iter().collect();
</code></pre>
<h1 id="heading-string">String</h1>
<p>The Rust String and str types represent text using the UTF-8 encoding form, which means they can contain characters that are more than one byte in size. Because of this, you cannot directly index into a <code>String</code> or <code>&amp;str</code> using the square bracket syntax like <code>s[1]</code> or <code>s[2]</code>.</p>
<h2 id="heading-access-characters-at-a-specific-position">Access Characters at a Specific Position</h2>
<p>The <code>chars()</code> method returns an iterator over the characters (<code>char</code> type) of a string. You can use the <code>nth()</code> method to get the character at a specific index. <code>nth()</code> returns an <code>Option&lt;char&gt;</code>, so you need to handle the case where the index is out of bounds. For example, <code>nth(1)</code> retrieves the character at index 1 (second character). This method accounts for multi-byte characters and is safe for UTF-8 strings. <em>The time complexity of</em> <code>nth()</code> <em>is O(n), as it iterates through the string up to the nth character.</em></p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"Hello"</span>);
<span class="hljs-keyword">let</span> c1 = s.chars().nth(<span class="hljs-number">1</span>);
<span class="hljs-keyword">let</span> c2 = s.chars().nth(<span class="hljs-number">2</span>);
</code></pre>
<p>You can collect the characters into a vector and then index directly. If you need frequent random access the can prefer this method.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"Hello"</span>);
<span class="hljs-keyword">let</span> chars: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">char</span>&gt; = s.chars().collect();
<span class="hljs-keyword">let</span> c1 = chars[<span class="hljs-number">1</span>];
</code></pre>
<h2 id="heading-remove-spaces-from-a-string">Remove Spaces from a String</h2>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"Hello World!"</span>);
<span class="hljs-comment">//Using the replace Method</span>
<span class="hljs-keyword">let</span> s_no_spaces = s.replace(<span class="hljs-string">" "</span>, <span class="hljs-string">""</span>);
</code></pre>
<p>You can iterate over each character, filter out the spaces, and collect the result into a new <code>String</code>.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> s1: <span class="hljs-built_in">String</span> = s.chars().filter(|&amp;c| c != <span class="hljs-string">' '</span>).collect();

<span class="hljs-keyword">let</span> s2: <span class="hljs-built_in">String</span> = s.chars().filter(|c| !c.is_whitespace()).collect();
<span class="hljs-comment">//Using the retain Method</span>
s.retain(|c| c != <span class="hljs-string">' '</span>);
</code></pre>
<p>Methods that consume the string (like <code>replace</code> and <code>filter</code>) create a new <code>String</code>, so you need to assign the result to a new variable.</p>
<p>The <code>is_whitespace()</code> method checks for Unicode whitespace characters, making it robust for international text. Using <code>retain</code> modifies the string in place and can be more efficient since it doesn't create an intermediate collection.</p>
<h2 id="heading-transforming-strings-lowercase-conversion-and-filtering"><strong>Transforming Strings: Lowercase Conversion and Filtering</strong></h2>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"Hello, World! 123"</span>);
s.retain(|c| c.is_alphanumeric());
s = s.to_ascii_lowercase();
</code></pre>
<p>You can iterate over each character in the string, convert it to lowercase, filter out non-alphanumeric characters, and collect the result into a new <code>String</code>.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> s = <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"Hello, World! 123"</span>);
<span class="hljs-keyword">let</span> cleaned: <span class="hljs-built_in">String</span> = s
    .chars()
    .filter(|c| c.is_alphanumeric())
    .map(|c| c.to_ascii_lowercase())
    .collect();
</code></pre>
<h2 id="heading-split-a-string-by-spaces">Split a String by Spaces</h2>
<p>The <code>split_whitespace()</code> method splits a string slice (<code>&amp;str</code>) on Unicode whitespace characters and returns an iterator over the substrings. The type <code>Vec&lt;&amp;str&gt;</code> means the vector contains string slices referencing the original string <code>s</code>. <code>split_whitespace()</code> automatically ignores leading and trailing whitespace. <code>split_whitespace()</code> splits on any Unicode whitespace character, including spaces, tabs (<code>\t</code>), newlines (<code>\n</code>), and carriage returns (<code>\r</code>).</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> words: <span class="hljs-built_in">Vec</span>&lt;&amp;<span class="hljs-built_in">str</span>&gt; = s.split_whitespace().collect();
<span class="hljs-comment">//If You Need Vec&lt;String&gt;</span>
<span class="hljs-keyword">let</span> words: <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">String</span>&gt; = s
        .split_whitespace()
        .map(|s| s.to_string())
        .collect();
<span class="hljs-keyword">let</span> words: <span class="hljs-built_in">Vec</span>&lt;&amp;<span class="hljs-built_in">str</span>&gt; = s.split(<span class="hljs-string">' '</span>).collect();
</code></pre>
<p><code>split()</code> method can be used with a space delimiter. But consecutive spaces result in empty strings (<code>""</code>) in the output. <code>split(' ')</code> will include empty strings.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> words: <span class="hljs-built_in">Vec</span>&lt;&amp;<span class="hljs-built_in">str</span>&gt; = s.split(<span class="hljs-string">' '</span>).collect();
<span class="hljs-comment">//To filter out empty strings</span>
<span class="hljs-keyword">let</span> words: <span class="hljs-built_in">Vec</span>&lt;&amp;<span class="hljs-built_in">str</span>&gt; = s
        .split(<span class="hljs-string">' '</span>)
        .filter(|&amp;s| !s.is_empty())
        .collect();
</code></pre>
<h2 id="heading-joining-a-vector-of-strings">Joining a Vector of Strings</h2>
<p>You can use the <code>join()</code> method on a <code>Vec&lt;String&gt;</code> or a <code>Vec&lt;&amp;str&gt;</code>. This method concatenates the elements of the vector, placing a separator between them.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> words = <span class="hljs-built_in">vec!</span>[<span class="hljs-string">"Hello"</span>, <span class="hljs-string">"world"</span>];
<span class="hljs-keyword">let</span> sentence = words.join(<span class="hljs-string">" "</span>);
words[<span class="hljs-number">1</span>] = <span class="hljs-string">"Rust"</span>;
<span class="hljs-comment">// The sentence remains unchanged</span>
<span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>, sentence);  <span class="hljs-comment">// Output: Hello world</span>
<span class="hljs-comment">// Print the modified vector</span>
<span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, words);  <span class="hljs-comment">// Output: ["Hello", "Rust"]</span>
</code></pre>
<p>The <code>join()</code> method does <strong>not</strong> consume the vector so you can access or modify it later. <code>join()</code> creates a <strong>new, separate copy</strong> of the joined string, and any changes to the original vector will not affect the <code>sentence</code> string.</p>
<h2 id="heading-building-a-character-frequency-hashmap-from-a-string"><strong>Building a Character Frequency HashMap from a String</strong></h2>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> freq_map = HashMap::new();
<span class="hljs-keyword">for</span> c <span class="hljs-keyword">in</span> s.chars() {
    *freq_map.entry(c).or_insert(<span class="hljs-number">0</span>) += <span class="hljs-number">1</span>;
}
</code></pre>
<h1 id="heading-iterators">Iterators</h1>
<p>Iterators are lazy, they don't compute anything until they are consumed.</p>
<h1 id="heading-ownership-reference-and-mutability"><strong>Ownership</strong>, <strong>reference and</strong> <strong>mutability</strong></h1>
<h2 id="heading-passing-references">Passing references</h2>
<p>Use <code>&amp;</code> (e.g., <code>&amp;v</code> for immutable reference, <code>&amp;mut v</code> for mutable reference). If you pass <code>&amp;v</code>, you are passing a <strong>borrowed immutable reference</strong> of <code>v</code>. <strong>When accepting a reference in a function</strong>, declare the parameter as <code>&amp;Type</code> to signify that the function will accept an immutable reference.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">my_function</span></span>(v: &amp;<span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt;)
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">modify_vector</span></span>(v: &amp;<span class="hljs-keyword">mut</span> <span class="hljs-built_in">Vec</span>&lt;<span class="hljs-built_in">i32</span>&gt;)
</code></pre>
<p><code>&amp;mut v</code> creates a <strong>mutable reference</strong> to the vector <code>v</code>. You can modify <code>v</code> directly through this reference. The original <code>v</code> remains owned by the original scope, but you have mutable access to it.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Keep practicing to get better at Rust. If any syntax or code that you use a lot in your daily coding, please leave a comment! I'll add new sections based on your feedback!</p>
]]></content:encoded></item><item><title><![CDATA[The Essential C++ STL Cheat sheet]]></title><description><![CDATA[This cheat sheet provides a quick reference to the most commonly used operations and features of std::vector in C++.
Vectors
Vectors are a part of the C++ Standard Template Library (STL) and are one of the most commonly used sequence containers. They...]]></description><link>https://siddharthqs.com/the-essential-c-stl-cheat-sheet</link><guid isPermaLink="true">https://siddharthqs.com/the-essential-c-stl-cheat-sheet</guid><category><![CDATA[stl]]></category><category><![CDATA[C++]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[vector]]></category><category><![CDATA[sorting]]></category><dc:creator><![CDATA[Siddharth]]></dc:creator><pubDate>Wed, 07 Aug 2024 03:26:31 GMT</pubDate><content:encoded><![CDATA[<p>This cheat sheet provides a quick reference to the most commonly used operations and features of <code>std::vector</code> in C++.</p>
<h1 id="heading-vectors">Vectors</h1>
<p>Vectors are a part of the C++ Standard Template Library (STL) and are one of the most commonly used sequence containers. They provide a dynamic array that can grow and shrink in size as needed. The key points about vectors:</p>
<ul>
<li><p><strong>Dynamic Size and Automatic Memory Management</strong>: Unlike arrays, vectors can dynamically resize themselves when elements are added or removed. This makes them more flexible and easier to use when the number of elements is not known in advance. They allocate memory as needed and deallocate it when it is no longer required.</p>
</li>
<li><p><strong>Contiguous Memory</strong>: Vectors store elements in contiguous memory locations, which means that elements can be accessed using pointer arithmetic. This also ensures that vectors are cache-friendly and provide fast access to elements.</p>
</li>
<li><p><strong>Iterators</strong>: Vectors support iterators, which are objects that point to elements within the container. Iterators provide a way to traverse the elements of the vector and perform operations on them.</p>
</li>
</ul>
<h2 id="heading-vector-basics">Vector Basics</h2>
<h3 id="heading-initialize-a-vector">Initialize a vector</h3>
<pre><code class="lang-cpp"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">vector</span> vec;
<span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">vector</span> <span class="hljs-title">vec</span><span class="hljs-params">(<span class="hljs-number">10</span>)</span></span>; <span class="hljs-comment">// Initializes a vector of size 10</span>
<span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">vector</span> <span class="hljs-title">vec</span><span class="hljs-params">(<span class="hljs-number">10</span>, <span class="hljs-number">5</span>)</span></span>; <span class="hljs-comment">//Size 10 with all elements set to 5</span>
<span class="hljs-built_in">std</span>::<span class="hljs-built_in">vector</span> vec = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}; Initializes a <span class="hljs-built_in">vector</span> of size <span class="hljs-number">10</span> with all elements <span class="hljs-built_in">set</span> to <span class="hljs-number">5</span>
</code></pre>
<p>Initialization from an Array, Vec, Range and Move:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">int</span> arr[] = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}; 
<span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">vector</span> <span class="hljs-title">vec</span><span class="hljs-params">(<span class="hljs-built_in">std</span>::begin(arr), <span class="hljs-built_in">std</span>::end(arr))</span></span>;
<span class="hljs-comment">//Another Vector</span>
<span class="hljs-built_in">std</span>::<span class="hljs-built_in">vector</span> vec1 = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}; 
<span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">vector</span> <span class="hljs-title">vec2</span><span class="hljs-params">(vec1)</span></span>; <span class="hljs-comment">// Copy constructor</span>
<span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">vector</span> <span class="hljs-title">vec3</span><span class="hljs-params">(vec1.begin(), vec1.begin() + <span class="hljs-number">3</span>)</span></span>; <span class="hljs-comment">// Initializes with the first three elements</span>
<span class="hljs-comment">//Move Initialization</span>
<span class="hljs-function"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">vector</span> <span class="hljs-title">vec4</span><span class="hljs-params">(<span class="hljs-built_in">std</span>::move(vec1))</span></span>; <span class="hljs-comment">// vec1 is now empty</span>
<span class="hljs-comment">//Assign method</span>
<span class="hljs-built_in">std</span>::<span class="hljs-built_in">vector</span> vec; 
vec.assign(<span class="hljs-number">10</span>, <span class="hljs-number">5</span>); <span class="hljs-comment">// Assigns 10 elements with value 5</span>
</code></pre>
<h3 id="heading-adding-elements">Adding Elements</h3>
<ul>
<li><p>Using <code>push_back</code>: Adds an element to the end of the vector.</p>
</li>
<li><p>Using <code>emplace_back</code>: Constructs an element in place at the end of the vector.</p>
</li>
<li><p>Using <code>insert</code>: Inserts elements at a specified position in the vector.</p>
</li>
<li><p>Using <code>emplace</code>: Constructs an element in place at a specified position in the vector.</p>
</li>
</ul>
<pre><code class="lang-cpp"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">vector</span> vec; 
<span class="hljs-comment">// Using push_back</span>
vec.push_back(<span class="hljs-number">1</span>);
<span class="hljs-comment">// Using emplace_back</span>
vec.emplace_back(<span class="hljs-number">3</span>);
<span class="hljs-comment">// Using insert</span>
vec.insert(vec.begin(), <span class="hljs-number">0</span>); <span class="hljs-comment">// Inserts 0 at the beginning</span>
vec.insert(vec.begin() + <span class="hljs-number">2</span>, <span class="hljs-number">5</span>); <span class="hljs-comment">// Inserts 5 at the third position</span>
<span class="hljs-comment">// Using emplace</span>
vec.emplace(vec.begin() + <span class="hljs-number">1</span>, <span class="hljs-number">6</span>); <span class="hljs-comment">// Constructs 6 at the second position</span>
</code></pre>
<p><strong>Difference between push_back and emplace_back</strong></p>
<p><code>push_back</code> adds an element to the end of the vector. It takes an existing object and copies or moves it into the vector.</p>
<pre><code class="lang-cpp"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">std</span>::<span class="hljs-built_in">string</span>&gt; vec; 
<span class="hljs-built_in">std</span>::<span class="hljs-built_in">string</span> str = <span class="hljs-string">"Hello"</span>; 
vec.push_back(str); <span class="hljs-comment">// Copies str into the vector</span>
</code></pre>
<p><code>emplace_back</code> constructs an element in place at the end of the vector. It forwards the arguments to the constructor of the element, avoiding unnecessary copies or moves.</p>
<pre><code class="lang-cpp"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">vector</span>&lt;<span class="hljs-built_in">std</span>::<span class="hljs-built_in">string</span>&gt; vec; 
vec.emplace_back(<span class="hljs-string">"Hello"</span>); <span class="hljs-comment">// Constructs the string directly in the vector</span>
</code></pre>
<p><code>emplace_back</code> constructs the element in place, while <code>push_back</code> requires an existing object. <code>emplace_back</code> can be more efficient as it avoids unnecessary copies or moves. <em><mark>Use emplace_back when you want to construct the element directly in the container, and push_back when you have an existing object to add.</mark></em></p>
<p>Similarly, <code>emplace</code> constructs the element in place, while <code>insert</code> requires an existing object. And you should emplace when you want to construct the element directly in the container, and insert when you have an existing object to add.</p>
<h3 id="heading-accessing-elements">Accessing Elements</h3>
<ul>
<li><pre><code class="lang-cpp">  <span class="hljs-keyword">int</span> first = vec.front()  <span class="hljs-comment">// Using front method</span>
  <span class="hljs-keyword">int</span> second = vec.at(<span class="hljs-number">1</span>);  <span class="hljs-comment">// Using the at() method (with bounds checking)</span>
  <span class="hljs-keyword">int</span> third = vec[<span class="hljs-number">2</span>];      <span class="hljs-comment">// Using the subscript operator</span>
  <span class="hljs-keyword">int</span> last = vec.back();   <span class="hljs-comment">// Using back method</span>
  <span class="hljs-keyword">auto</span> it = vec.begin();   
  <span class="hljs-keyword">int</span> fourth = *(it+<span class="hljs-number">3</span>);    <span class="hljs-comment">//Using Iterators</span>
</code></pre>
</li>
</ul>
<h3 id="heading-removing-elements">Removing Elements</h3>
<pre><code class="lang-cpp">vec.pop_back(); <span class="hljs-comment">// Removes the last element</span>
vec.erase(vec.begin()+<span class="hljs-number">2</span>); <span class="hljs-comment">// Removes the element at index 2</span>
vec.erase(vec.begin() + <span class="hljs-number">4</span>, vec.begin() + <span class="hljs-number">6</span>); <span class="hljs-comment">// Using erase to remove a range of elements</span>
vec.clear(); <span class="hljs-comment">// Removes all elements</span>
</code></pre>
<h3 id="heading-the-remove-algorithm">The remove algorithm</h3>
<p>The remove algorithm is part of the C++ Standard Library and is used to remove elements from a range. It does not actually remove elements from the container but rather shifts the elements to be removed to the end of the container and returns an iterator to the new end of the range. It is typically used in conjunction with the erase method of the container to actually remove the elements.</p>
<pre><code class="lang-cpp"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">vector</span>&lt;<span class="hljs-keyword">int</span>&gt; vec = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">3</span>, <span class="hljs-number">6</span>, <span class="hljs-number">3</span>, <span class="hljs-number">7</span>};
<span class="hljs-comment">// Using remove to shift elements to be removed to the end</span>
<span class="hljs-keyword">auto</span> new_end = <span class="hljs-built_in">std</span>::remove(vec.begin(), vec.end(), <span class="hljs-number">3</span>);
<span class="hljs-comment">// Erase the elements from the container</span>
vec.erase(new_end, vec.end());

<span class="hljs-comment">// Erase-Remove Idiom</span>
vec.erase(<span class="hljs-built_in">std</span>::remove(vec.begin(), vec.end(), <span class="hljs-number">3</span>), vec.end());
</code></pre>
<p>std::remove shifts all elements equal to 3 to the end of the vector and returns an iterator to the new end.</p>
<h3 id="heading-iterating-over-a-vector">Iterating Over a Vector</h3>
<pre><code class="lang-cpp"><span class="hljs-comment">// Using Index-Based Loop</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">size_t</span> i = <span class="hljs-number">0</span>; i &lt; vec.size(); ++i) {
        <span class="hljs-built_in">cout</span> &lt;&lt; vec[i] &lt;&lt; <span class="hljs-string">" "</span>;
    }
<span class="hljs-comment">// Using Range-Based For Loop</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> val : vec) {
    <span class="hljs-built_in">cout</span> &lt;&lt; val &lt;&lt; <span class="hljs-string">" "</span>;
}
<span class="hljs-comment">// Using Iterators</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">auto</span> it = vec.begin(); it != vec.end(); ++it) {
    <span class="hljs-built_in">cout</span> &lt;&lt; *it &lt;&lt; <span class="hljs-string">" "</span>;
}
<span class="hljs-comment">// Using for_each Algorithm</span>
<span class="hljs-built_in">std</span>::for_each(vec.begin(), vec.end(), [](<span class="hljs-keyword">int</span> val) {
        <span class="hljs-built_in">cout</span> &lt;&lt; val &lt;&lt; <span class="hljs-string">" "</span>;
});
</code></pre>
<h2 id="heading-memory-management-functions">Memory Management Functions</h2>
<p>When a vector is created, it allocates a small amount of memory. As elements are added, if the current capacity is exceeded, the vector allocates more memory (usually doubling the current capacity). When the vector's capacity is exceeded, it allocates a new block of memory with a larger capacity. The existing elements are copied to the new memory block, and the old memory is deallocated. This process can be costly in terms of time and memory, which is why vectors allocate more memory than needed to minimize reallocations.</p>
<ul>
<li><p><code>reserve</code>: Requests that the vector capacity be at least enough to contain n elements. This can prevent multiple reallocations if the number of elements to be added is known in advance.</p>
</li>
<li><p><code>shrink_to_fit</code>: Requests the container to reduce its capacity to fit its size. This is a non-binding request to reduce memory usage.</p>
</li>
<li><p><code>capacity</code>: Returns the number of elements that the vector can hold before needing to allocate more memory.</p>
</li>
</ul>
<pre><code class="lang-cpp"><span class="hljs-built_in">vector</span> vec; vec.reserve(<span class="hljs-number">100</span>); <span class="hljs-comment">// Pre-allocate memory for 100 elements</span>
<span class="hljs-built_in">vector</span> vec = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}; 
vec.shrink_to_fit(); <span class="hljs-comment">// Reduce capacity to match size</span>
<span class="hljs-comment">//Capacity</span>
<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Capacity: "</span> &lt;&lt; vec.capacity();
</code></pre>
<h2 id="heading-vector-algorithms">Vector Algorithms</h2>
<pre><code class="lang-cpp"><span class="hljs-built_in">std</span>::sort(vec.begin(), vec.end()); <span class="hljs-comment">// Sort ascending order by default</span>
<span class="hljs-keyword">bool</span> found = <span class="hljs-built_in">std</span>::binary_search(vec.begin(), vec.end(), <span class="hljs-number">3</span>);
<span class="hljs-keyword">auto</span> it = <span class="hljs-built_in">std</span>::find(vec.begin(), vec.end(), <span class="hljs-number">8</span>); <span class="hljs-comment">//searches for the first occurrence</span>
<span class="hljs-built_in">std</span>::reverse(vec.begin(), vec.end()); <span class="hljs-comment">//reverses the order of elements </span>
<span class="hljs-keyword">int</span> sum = <span class="hljs-built_in">std</span>::accumulate(vec.begin(), vec.end(), initial_value); 
<span class="hljs-keyword">int</span> count_3 = <span class="hljs-built_in">std</span>::count(vec.begin(), vec.end(), <span class="hljs-number">3</span>); <span class="hljs-comment">//counts the number of occurrences</span>
<span class="hljs-comment">// Count If counts the number of elements in a vector that satisfy a given predicate.</span>
<span class="hljs-keyword">int</span> count_greater_than_4 = <span class="hljs-built_in">std</span>::count_if(vec.begin(), vec.end(), [](<span class="hljs-keyword">int</span> val) { <span class="hljs-keyword">return</span> val &gt; <span class="hljs-number">4</span>; });
<span class="hljs-comment">//The min_element algorithm finds the smallest element in a vector.</span>
<span class="hljs-keyword">auto</span> min_it = <span class="hljs-built_in">std</span>::min_element(vec.begin(), vec.end());
<span class="hljs-comment">//The max_element algorithm finds the largest element in a vector.</span>
<span class="hljs-keyword">auto</span> max_it = <span class="hljs-built_in">std</span>::max_element(vec.begin(), vec.end());
<span class="hljs-comment">//The equal algorithm checks if two vectors are equal.</span>
<span class="hljs-keyword">bool</span> are_equal = <span class="hljs-built_in">std</span>::equal(vec.begin(), vec.end(), vec2.begin());
</code></pre>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Vectors and Maps in C++ are a powerful and flexible container provided by the Standard Template Library (STL).</p>
]]></content:encoded></item><item><title><![CDATA[The Silent Troublemaker: Issues with operator [ ] in std::map in C++]]></title><description><![CDATA[While operator [] for accessing elements in std::map or std::unordered_map is convenient and familiar to those accustomed to working with dictionaries in other languages, it comes with some potential pitfalls and debugging nightmares in C++. Beware t...]]></description><link>https://siddharthqs.com/the-silent-troublemaker-issues-with-operator-in-stdmap-in-c</link><guid isPermaLink="true">https://siddharthqs.com/the-silent-troublemaker-issues-with-operator-in-stdmap-in-c</guid><dc:creator><![CDATA[Siddharth]]></dc:creator><pubDate>Sun, 04 Aug 2024 01:00:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1722732916154/8862d472-eb00-4992-bbde-84f253a994a1.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>While operator [] for accessing elements in <code>std::map</code> or <code>std::unordered_map</code> is convenient and familiar to those accustomed to working with dictionaries in other languages, it comes with some potential pitfalls and debugging nightmares in C++. Beware the brackets '[ ]', as understanding their limitations is essential to avoid unexpected results in your C++ code.</p>
<h1 id="heading-implicit-insertion">Implicit Insertion</h1>
<p>When you use <code>operator[]</code> to access a key that does not exist in the map, <code>std::map</code> will implicitly insert a new element with that key and a default-constructed value. This can lead to unintended side effects.</p>
<pre><code class="lang-cpp"><span class="hljs-built_in">std</span>::<span class="hljs-built_in">map</span>&lt;<span class="hljs-keyword">char</span>, <span class="hljs-keyword">int</span>&gt; my_map;
<span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Size of map: "</span> &lt;&lt; my_map.size() &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>; 

<span class="hljs-keyword">int</span> value = my_map[<span class="hljs-string">'a'</span>]; <span class="hljs-comment">// 'a' is not in the map, so it gets added with value 0.    </span>
<span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Value for key 'a': "</span> &lt;&lt; value &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
<span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Size of map: "</span> &lt;&lt; my_map.size() &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>; <span class="hljs-comment">// Size is now 1</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722724283157/c32a7755-5980-4cfd-95a0-727a3a476d3e.png" alt /></p>
<p><strong>Issue</strong>: This implicit insertion can lead to bugs if you are only intending to check for the existence of a key or to retrieve a value without modifying the map and expect a exception if key is not present.</p>
<p>Even if you are performing read-only operations on the map, using <code>operator[]</code> can unintentionally modify the map by inserting new elements.</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">map</span>&lt;<span class="hljs-keyword">char</span>, <span class="hljs-keyword">int</span>&gt; my_map;

    <span class="hljs-comment">// Read-only check</span>
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Size of map: "</span> &lt;&lt; my_map.size() &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
    <span class="hljs-keyword">if</span> (my_map[<span class="hljs-string">'a'</span>] &gt; <span class="hljs-number">0</span>) {
        <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"'a' is present with a positive value"</span> &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
    }
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Size of map: "</span> &lt;&lt; my_map.size() &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>; <span class="hljs-comment">// Size is now 1, even though we intended to just check</span>
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span>&lt;&lt;<span class="hljs-string">"Value at a: "</span>&lt;&lt;my_map[<span class="hljs-string">'a'</span>]&lt;&lt;<span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722726767975/fca561d4-35e9-4f1c-b746-31ab7fbd863a.png" alt /></p>
<p><strong>Issue</strong>: The map is modified even when the intention was just to check the value.</p>
<h1 id="heading-default-constructor-is-called">Default Constructor is called</h1>
<p>When a new key is added implicitly using <code>operator[]</code>, the value is default-constructed. For primitive types like <code>int</code> or <code>double</code>, this means zero initialization. However, for user-defined types, the default constructor is called, which might not be the desired behavior.</p>
<pre><code class="lang-cpp"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">MyStruct</span> {</span>
    MyStruct() {
        data =<span class="hljs-number">10</span>;
        <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Default constructor called"</span> &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
    }
    <span class="hljs-keyword">int</span> data;
};
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">map</span>&lt;<span class="hljs-keyword">char</span>, MyStruct&gt; my_map;
    MyStruct value = my_map[<span class="hljs-string">'a'</span>]; <span class="hljs-comment">// Default constructor for MyStruct is called</span>
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span>&lt;&lt;<span class="hljs-string">"Value of data: "</span>&lt;&lt;value.data&lt;&lt;<span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Size of map: "</span> &lt;&lt; my_map.size() &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>; <span class="hljs-comment">// Size is now 1</span>
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722724878555/c223be2d-03b7-4bb2-b528-199a014f7f01.png" alt /></p>
<p><strong>Issue</strong>: This default construction might have performance implications or unintended side effects if the default constructor does more than simple initialization.</p>
<h1 id="heading-performance-overhead">Performance Overhead</h1>
<p>In scenarios where <code>operator[]</code> is used for repeated lookups and the key does not exist, it results in multiple implicit insertions with default values, which can add unnecessary performance overhead.</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">map</span>&lt;<span class="hljs-keyword">char</span>, <span class="hljs-keyword">int</span>&gt; my_map;
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Size of map: "</span> &lt;&lt; my_map.size() &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">char</span> c = <span class="hljs-string">'a'</span>; c &lt;= <span class="hljs-string">'z'</span>; ++c) {
        <span class="hljs-keyword">int</span> value = my_map[c]; <span class="hljs-comment">// Each lookup inserts a default value if the key does not exist</span>
    }

    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Size of map: "</span> &lt;&lt; my_map.size() &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>; <span class="hljs-comment">// Size is now 26</span>
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722726958878/999d42ef-29fe-41e9-96a6-6a1d0465e04e.png" alt /></p>
<p><strong>Issue</strong>: This can lead to a larger map with many unnecessary default-constructed values, impacting memory usage and performance. In this example you end up 26 elements in the map.</p>
<h1 id="heading-what-you-should-use-instead">What you should use instead</h1>
<p>To avoid the issues with <code>operator[]</code>, you can use the following alternatives:</p>
<h2 id="heading-at-method"><code>at</code> Method</h2>
<p><code>at</code> method throws an exception if the key does not exist. You should use this when you expect the key to be present.</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">map</span>&lt;<span class="hljs-keyword">char</span>, <span class="hljs-keyword">int</span>&gt; my_map;
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">int</span> value = my_map.at(<span class="hljs-string">'a'</span>); <span class="hljs-comment">// Throws std::out_of_range if 'a' does not exist</span>
    } <span class="hljs-keyword">catch</span> (<span class="hljs-keyword">const</span> <span class="hljs-built_in">std</span>::out_of_range&amp; e) {
        <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Key 'a' not found"</span> &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
    }
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1722727276201/a0565979-fe18-45f6-afd3-d1fffb7c05aa.png" alt /></p>
<h2 id="heading-find-method"><code>find</code> Method</h2>
<p><code>find</code> method returns an iterator to the element or <code>end()</code> if the key does not exist. you can use this as well for existence checks without modifying the map.</p>
<pre><code class="lang-cpp"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">map</span>&lt;<span class="hljs-keyword">char</span>, <span class="hljs-keyword">int</span>&gt; my_map;
    <span class="hljs-keyword">auto</span> it = my_map.find(<span class="hljs-string">'a'</span>);
    <span class="hljs-keyword">if</span> (it != my_map.end()) {
        <span class="hljs-keyword">int</span> value = it-&gt;second;
        <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Value for key 'a': "</span> &lt;&lt; value &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Key 'a' not found"</span> &lt;&lt; <span class="hljs-built_in">std</span>::<span class="hljs-built_in">endl</span>;
    }
}
</code></pre>
<h1 id="heading-conclusion">Conclusion</h1>
<p>The <code>operator[]</code> in <code>std::map</code> or in <code>std::unordered_map</code> offers easy element access, but it may cause unexpected results. For read-only operations or when checking for the existence of a key, it's better to use methods like <code>at</code>, <code>find</code>, or <code>count</code> to avoid potential issues. Understanding these nuances will help you use <code>std::map</code> more effectively and prevent unintended side effects in your C++ code.</p>
]]></content:encoded></item><item><title><![CDATA[The POV (Percentage of Volume) Algorithm]]></title><description><![CDATA[One word commonly appearing in algorithmic trading landscape is "POV" – Percentage of Volume. Understanding the POV is crucial for traders seeking efficient execution strategies that depend on the shifting market conditions. In this blog post, we wil...]]></description><link>https://siddharthqs.com/the-pov-percentage-of-volume-algorithm</link><guid isPermaLink="true">https://siddharthqs.com/the-pov-percentage-of-volume-algorithm</guid><category><![CDATA[algorithms]]></category><category><![CDATA[trading, ]]></category><category><![CDATA[algotrading]]></category><dc:creator><![CDATA[Siddharth]]></dc:creator><pubDate>Mon, 16 Oct 2023 04:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1704467623811/d5d1cbc3-c963-4df5-8d4b-c51163ec2fe0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>One word commonly appearing in algorithmic trading landscape is "POV" – Percentage of Volume. Understanding the POV is crucial for traders seeking efficient execution strategies that depend on the shifting market conditions. In this blog post, we will discuss the concept of POV and how it works and provide examples.</p>
<h2 id="heading-overview-of-pov">Overview of POV</h2>
<p>The POV is an order execution trading strategy that allows traders to execute the desired percentage of the total market volume called <strong><em>participation rate</em></strong> over a specified period. It's an adaptive strategy designed to adjust the order size dynamically based on prevailing or forecasted market volume in real-time.</p>
<p>Unlike TWAP / VWAP, which follows a fixed schedule, the POV algorithm changes its trading in real-time to ensure a consistent participation rate. The POV, however, has an intuition of the VWAP algorithm, but in real-time. The VWAP algorithm trades more when the volume is historically high and less when the volume is historically low. The POV algorithm trades more when the market trades more and less when the market trades less.</p>
<h2 id="heading-how-pov-works"><strong>How POV Works</strong></h2>
<p>Assume a trader intends to execute 5% of total market volume during an hour using a POV algorithm. The algorithm will seek to trade 500 shares for every 10,000 shares that trade in the following hour. The algorithm will attempt to submit an order for 50 shares for every 1000 shares, e.g., if 950 shares trade in 1 minute, the algorithm will send a limit order or market order (for more aggressive execution) for 50 shares (total volume traded would be 950+50 = 1000). And if another 1000 shares trades in the market during the following 30 minutes, the algo will have traded only 100 shares in 31 mins (1+30 mins). <strong><em>Generally, for the POV algorithm, the schedule is updated on a tick-by-tick basis, and it waits for trading to occur and then participates only afterward.</em></strong></p>
<h2 id="heading-market-impact-and-considerations-for-the-pov"><strong>Market Impact and Considerations for the POV</strong></h2>
<p>Since the POV algorithm must trade more aggressively to avoid falling behind schedule, it often uses market orders rather than limit orders, placing orders only after the trading volume has happened. Spread expenses increase as a result. The POV is volume-responsive and ultimately becomes a liquidity taker rather than a liquidity generator. It trades immediately following the volume surge, responds to the previous volume, and has the potential to significantly affect the price if another trader has made a similar move. Another increase in volume would result from this, which would encourage trading by additional parties. The POV would trade more aggressively to maintain the target rate due to this feedback cycle at the expense of higher market impact costs.</p>
<h3 id="heading-inability-to-guarantee-completion"><strong>Inability to Guarantee Completion</strong></h3>
<p>POV algorithms cannot guarantee that an order will be executed within the specified time frame. Market conditions, particularly low liquidity, may result in partial fills or the inability to complete the order within the desired period.</p>
<h3 id="heading-not-suitable-for-all-securities"><strong>Not Suitable for All Securities</strong></h3>
<p>Illiquid stocks have short and isolated bursts of activity than more liquid stocks. The POV would respond to such spikes quickly and would have more spread and market impact cost. Intuitively, the POV should be more effective than TWAP / VWAP with the higher volume. However, it ends up being reactive and suboptimal.</p>
<h3 id="heading-implementation-challenges"><strong>Implementation Challenges</strong></h3>
<p>POV algorithm implementation and maintenance can be challenging and need careful calibration. Traders must constantly evaluate and modify parameters; they must pay attention to order sizes, the number of open orders, the intervals between orders, the nature of market dynamics, order book sizes, and hidden liquidity. Additional risk management and real-time monitoring are crucial to navigate the complexities introduced by the interaction of Iceberg Orders.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>While the POV has several advantages over other algorithms, such as TWAP and VWAP, it also has limitations and challenges. Nevertheless, with careful calibration and monitoring, POV can be a powerful tool for traders seeking to navigate the complexities of algorithmic trading. Traders must pay attention to its implementation details and can use its concept along with other algorithms, such as VWAP, to design custom execution trading algorithms.</p>
]]></content:encoded></item><item><title><![CDATA[Latency in Automated Trading System]]></title><description><![CDATA[Latency is the delay between a signal and a response. It is measured in units of time in seconds, milliseconds, microseconds, nanoseconds and so forth. Latency is an essential feature of any non-trivial mechanical or electronic system e.g. an automat...]]></description><link>https://siddharthqs.com/latency-in-automated-trading-system</link><guid isPermaLink="true">https://siddharthqs.com/latency-in-automated-trading-system</guid><category><![CDATA[trading, ]]></category><category><![CDATA[Automated Testing]]></category><category><![CDATA[high frequency trading]]></category><category><![CDATA[latency]]></category><dc:creator><![CDATA[Siddharth]]></dc:creator><pubDate>Mon, 09 Oct 2023 20:00:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/JyRTi3LoQnc/upload/fbdbd7274f3aff4e93e63e5f5738af82.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Latency is the delay between a signal and a response. It is measured in units of time in seconds, milliseconds, microseconds, nanoseconds and so forth. Latency is an essential feature of any non-trivial mechanical or electronic system e.g. an <strong><em>automated trading system.</em></strong></p>
<p>A standard way to measure latency is by determining the time it takes a given data packet to travel from source to destination and back, the round-trip time (RTT).</p>
<p>The data packet in the automated trading system is the message. A message is a standardized packet of data that enables a trader and an automated trading venue to communicate with each other. It is a primitive unit of valuable info that enables all the pre-trading, trading and post-trading activities. Messaging is the only way to affect the price formation process. Each message is time-stamped when it passes through a specific subsystem of an automated trading system.</p>
<h2 id="heading-types-of-latency">Types of Latency</h2>
<p>Here are the primary types of latency encountered in automated trading:</p>
<h3 id="heading-communication-latency">Communication latency</h3>
<p>Communication latency is the delay introduced during the transmission of data between different components of a trading system. This can be reduced by buying co-location services. It encompasses the time it takes for data to travel from the trader's system to various destinations, such as the exchange's servers, liquidity providers, or other trading platforms.</p>
<ul>
<li><strong>Reducing Communication Latency:</strong> Traders often seek to minimize communication latency by leveraging co-location services. Co-location involves placing their trading servers physically close to the exchange's servers.</li>
</ul>
<h3 id="heading-market-feed-latency"><strong>Market-Feed Latency</strong></h3>
<p>Market-feed latency refers to the delay in receiving market data updates from the exchange. This includes information about prices, trade executions, order book updates, and other critical market information.</p>
<ul>
<li><strong>Reducing Market-Feed Latency:</strong> To mitigate market-feed latency, traders often opt for proprietary data feeds provided by the exchange or a few data vendors. These proprietary feeds are optimized for speed and can provide market information faster than publicly available feeds for retail traders.</li>
</ul>
<h3 id="heading-trading-platform-latency"><strong>Trading Platform Latency</strong></h3>
<p>Trading platform latency encompasses the delay introduced within the trading platform itself. This latency is largely beyond the control of individual traders and is determined by the design and infrastructure of the trading platform they are using.</p>
<ul>
<li><strong>Trading Platform as a Given:</strong> Traders must accept trading platform latency as a given factor that is inherent to the platform they choose to use. While they can optimize their strategies and use low-latency communication channels, they may not have direct control over the latency introduced by the platform itself.</li>
</ul>
<blockquote>
<p>Latency moves volatility moves.</p>
</blockquote>
<h2 id="heading-matching-engine-processing-time">Matching engine processing time</h2>
<p>One of the critical aspects of automated trading is the speed at which orders are matched and executed within a trading platform's matching engine. The matching engine is the heart of an exchange or trading platform. Traders seek platforms with low-latency matching engines to ensure that their orders are executed swiftly.</p>
<h3 id="heading-best-bid-and-offer-bbo-messages"><strong>Best Bid and Offer (BBO) Messages</strong></h3>
<p>Messages that result in changes in the Best Bid and Offer (BBO) are of utmost importance in terms of the price formation process. The BBO represents the highest bid price and the lowest ask price in the order book. It takes more time for a platform to process BBO messages than a message that changes the lengths of existing queues.</p>
<h3 id="heading-depth-messages">Depth Messages</h3>
<p>Conversely, messages that add depth to the order book by introducing small orders or trading volume without changing the BBO have a less immediate impact on price formation. It doesn't move the mid-point price and takes less time to update the existing queues.</p>
<p>In conclusion, latency is a fundamental consideration in automated trading systems and the role of matching engine processing time and the different message types is essential for traders operating in automated trading environments. Communication latency and market-feed latency can often be managed by selecting the right services and infrastructure, while trading platform latency is a factor that traders must consider when choosing their trading platform.</p>
]]></content:encoded></item><item><title><![CDATA[Navigating Safely with `Option` in Rust]]></title><description><![CDATA[Rust is SERIOUS about safety and control over memory. Option type – an essential tool in Rust's arsenal that keeps your code safe and sound. Option is a fundamental type in Rust and is widely used for error handling, optional values, and more. You wo...]]></description><link>https://siddharthqs.com/navigating-safely-with-option-in-rust</link><guid isPermaLink="true">https://siddharthqs.com/navigating-safely-with-option-in-rust</guid><category><![CDATA[Rust]]></category><category><![CDATA[Null]]></category><category><![CDATA[pointers]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[json]]></category><dc:creator><![CDATA[Siddharth]]></dc:creator><pubDate>Sun, 08 Oct 2023 16:45:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/JvIwBruknXk/upload/81f25c63e8cea8c49f538248cd3f986c.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Rust is SERIOUS about safety and control over memory. <code>Option</code> type – an essential tool in Rust's arsenal that keeps your code safe and sound. <code>Option</code> is a fundamental type in Rust and is widely used for error handling, optional values, and more. You would often encounter with functions in Rust that return <code>Option</code> type. It encourages the safe handling of potentially absent or invalid values and helps prevent dreaded null pointer errors that plague C++.</p>
<h2 id="heading-introducing-option"><strong>Introducing</strong> Option</h2>
<p><code>Option</code> is an enumeration (enum) type that represents either a value or the absence of a value. It can either be "Some" or "None," helping you navigate the potentially missing or invalid values. It is defined by the standard library as follows:</p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">enum</span> <span class="hljs-title">Option</span></span>&lt;T&gt; {
    <span class="hljs-literal">Some</span>(T),
    <span class="hljs-literal">None</span>,
}
</code></pre>
<p>The Option enum is so useful that it’s even included in the prelude. In other words, if a value has a type that isn’t an Option, you can safely assume that the value isn’t null.</p>
<h3 id="heading-option-variants">Option Variants</h3>
<p><code>The option</code> has two variants:</p>
<ol>
<li><p><code>Some(T)</code>: Represents a value of type <code>T</code>. &lt;T&gt; is a generic type parameter. It indicates that a value is present.</p>
</li>
<li><p><code>None</code>: Represents the absence of a value.</p>
</li>
</ol>
<p>Some and None are used directly without the Option:: prefix as they are included in the prelude as well.</p>
<h2 id="heading-the-null-less-rust-coast">The Null-less Rust Coast</h2>
<p>Rust is free of the "null" feature that many other languages have. Null is a value that means there is no value there. In languages with null, variables can always be in one of two states: null or not-null. The problem? If you try to treat null as not-null, you’ll get an error and since null or not-null is a common property, it's easier to fall into this.</p>
<h2 id="heading-sailing-with-option"><strong>Sailing with</strong> <code>Option</code></h2>
<p>In Rust, <code>Option</code> is the ship, safeguarding you from these treacherous waters. Let's embark on this adventure with a simple example: Here the <code>fun1</code> function returns an <code>Option&lt;f64&gt;</code> which means it can either return <code>Some(f64)</code> or <code>None</code>.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">fun1</span></span>()-&gt;<span class="hljs-built_in">Option</span>&lt;<span class="hljs-built_in">f64</span>&gt;{
    <span class="hljs-keyword">let</span> x = <span class="hljs-number">0.0</span>;
    <span class="hljs-keyword">if</span> x ==<span class="hljs-number">0.0</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-literal">Some</span>(x);
    }
    <span class="hljs-keyword">else</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>;
    }
}
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>(){
    <span class="hljs-keyword">let</span> x = fun1();
    <span class="hljs-keyword">let</span> y = <span class="hljs-number">1.0</span>;
    <span class="hljs-keyword">let</span> sum = x+y;
}

error[E0369]: cannot add `{float}` to `<span class="hljs-built_in">Option</span>&lt;{float}&gt;`
 --&gt; src/main.rs:<span class="hljs-number">4</span>:<span class="hljs-number">16</span>
  |
<span class="hljs-number">4</span> |     <span class="hljs-keyword">let</span> sum = x+y;
  |               -^- {float}
  |               |
  |               <span class="hljs-built_in">Option</span>&lt;{float}&gt;
</code></pre>
<p>The expression <code>x + y</code> tries to add an <code>Option&lt;f64&gt;</code> (<code>x</code>) to a <code>f64</code> (<code>y</code>). This is not allowed because Rust's type system enforces safety, and it doesn't allow adding an <code>Option</code> to a regular value directly. You would need to handle the <code>Option</code> using match statements or other methods to extract the value from <code>Some</code> (if it exists) and then perform the addition.</p>
<p>The <code>Option</code> has a large number of methods that are useful in a variety of situations like this. You can use methods like <code>unwrap</code> or <code>unwrap_or</code> to handle the <code>Option</code> and get its value.</p>
<h3 id="heading-methods-to-work-with-option">Methods to work with <code>Option</code></h3>
<p>The <code>Option</code> enum provides several methods and associated functions that allow you to work with optional values (values that can be either <code>Some(value)</code> or <code>None</code>). Here are some of the commonly used methods for <code>Option</code>:</p>
<ol>
<li><p><code>unwrap()</code>: This method extracts the value from a <code>Some</code> variant and panics if the variant is <code>None</code>. It should be used with caution, as it can lead to a panic.</p>
</li>
<li><p><code>unwrap_or(default)</code>: Extracts the value from a <code>Some</code> variant or returns a default value if the variant is <code>None</code>. It provides a safer alternative to <code>unwrap()</code>.</p>
</li>
<li><p><code>unwrap_or_else(fn)</code>: Similar to <code>unwrap_or</code>, it takes a closure that computes and returns the default value if needed. This allows for lazy evaluation of the default value.</p>
</li>
<li><p><code>expect(msg)</code>: Similar to <code>unwrap()</code>, but it allows you to provide a custom error message that will be displayed if the variant is <code>None</code>.</p>
</li>
<li><p><code>is_some()</code>: Returns <code>true</code> if the variant is <code>Some</code>, indicate the presence of a value.</p>
</li>
<li><p><code>is_none()</code>: Returns <code>true</code> if the variant is <code>None</code>, indicating the absence of a value.</p>
</li>
<li><p><code>map(fn)</code>: Applies a function to the inner value if it's <code>Some</code> and return a new <code>Option</code> containing the result. If it's <code>None</code>, it returns <code>None</code>.</p>
</li>
<li><p><code>map_or(default, fn)</code>: Applies a function to the inner value if it's <code>Some</code>, return the result. If it's <code>None</code>, it returns the provided default value.</p>
</li>
</ol>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>(){
    <span class="hljs-keyword">let</span> x = fun1();
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>,x.unwrap_or(<span class="hljs-number">10.0</span>));
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>,x.unwrap_or_else(|| {fun2()}));
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>,x.expect(<span class="hljs-string">" It has None"</span>));
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>,x.is_some());
}
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">fun2</span></span>()-&gt;<span class="hljs-built_in">f64</span>{
    <span class="hljs-number">100.0</span>
}
<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">fun1</span></span>()-&gt;<span class="hljs-built_in">Option</span>&lt;<span class="hljs-built_in">f64</span>&gt;{
    <span class="hljs-keyword">let</span> x = <span class="hljs-number">0.0</span>;
    <span class="hljs-keyword">if</span> x ==<span class="hljs-number">0.0</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-literal">Some</span>(x);
    }
    <span class="hljs-keyword">else</span>{
        <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>;
    }
}
----------------------------Output---------------------
<span class="hljs-number">0</span>
<span class="hljs-number">0</span>
<span class="hljs-number">0</span>
<span class="hljs-literal">true</span>
</code></pre>
<h3 id="heading-pattern-matching-with-option">Pattern Matching with <code>Option</code></h3>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-keyword">let</span> x = fun1();
    <span class="hljs-keyword">match</span> x {
        <span class="hljs-literal">Some</span>(x) =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"The value is: {}"</span>, value),
        <span class="hljs-literal">None</span> =&gt; <span class="hljs-built_in">println!</span>(<span class="hljs-string">"No value found"</span>),
    }
}
</code></pre>
<p>In the code above, we use <code>match</code> to extract and handle the value inside the <code>Option</code>. When <code>Some</code>, we print the value; when <code>None</code>, we indicate that no value was found.</p>
<h3 id="heading-another-example-of-deserialize-and-serialize-json">Another example of Deserialize and Serialize JSON</h3>
<p>Let's see an example of JSON. You are working with JSON where a few attributes are optional. In the below example, let's assume style is optional, you could get JSON as input where style is absent.</p>
<pre><code class="lang-json"> {
<span class="hljs-attr">"current_price"</span>: <span class="hljs-number">100.0</span>
<span class="hljs-string">"style"</span>:<span class="hljs-string">"American"</span>
}
</code></pre>
<p>To handle this case, you could define struct as below:</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(Clone,Debug,Deserialize,Serialize)]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Contract</span></span> {
    <span class="hljs-keyword">pub</span> current_price: <span class="hljs-built_in">f64</span>,
    <span class="hljs-keyword">pub</span> style: <span class="hljs-built_in">Option</span>&lt;<span class="hljs-built_in">String</span>&gt;
}
<span class="hljs-keyword">pub</span> <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">EquityOption</span></span> {
    <span class="hljs-keyword">pub</span> current_price: <span class="hljs-built_in">f64</span>,
    <span class="hljs-keyword">pub</span> style: <span class="hljs-built_in">Option</span>&lt;<span class="hljs-built_in">String</span>&gt;,
}
</code></pre>
<pre><code class="lang-rust"><span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> contents = <span class="hljs-built_in">String</span>::new();
file.read_to_string(&amp;<span class="hljs-keyword">mut</span> contents).expect(<span class="hljs-string">"Failed to read JSON file"</span>);
<span class="hljs-keyword">let</span> data: utils::Contract = serde_json::from_str(&amp;contents)
                           .expect(<span class="hljs-string">"Failed to deserialize JSON"</span>)
<span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> contract = EquityOption {
    current_price: data.current_price,
    style: <span class="hljs-built_in">Option</span>::from(data.style.as_ref().unwrap_or(&amp;default_style))

error[E0308]: mismatched types
style : <span class="hljs-built_in">Option</span>::from(data.style.as_ref().unwrap_or(&amp;<span class="hljs-string">"European"</span>.to_string()))
  |                 ^^^^^^^^^^^^^^^^^^^^^^ expected `<span class="hljs-built_in">Option</span>&lt;<span class="hljs-built_in">String</span>&gt;`, found `<span class="hljs-built_in">Option</span>&lt;&amp;<span class="hljs-built_in">String</span>&gt;`
  |
  = note: expected <span class="hljs-class"><span class="hljs-keyword">enum</span> `<span class="hljs-title">Option</span></span>&lt;<span class="hljs-built_in">String</span>&gt;`
             found <span class="hljs-class"><span class="hljs-keyword">enum</span> `<span class="hljs-title">Option</span></span>&lt;&amp;<span class="hljs-built_in">String</span>&gt;`
</code></pre>
<p><code>Option::from</code> is used to convert a value of one type into an <code>Option</code> of that type.</p>
<p>We used <code>Option&lt;String&gt;</code> in our equity struct that is an <code>Option</code> that can either hold a <code>Some(String)</code> value. The <code>String</code> inside <code>Option&lt;String&gt;</code> is owned, meaning we have exclusive ownership of this String.</p>
<p>The above code gives an error because we get the <code>Option&lt;&amp;String&gt;</code> type. <code>Option&lt;&amp;String&gt;</code> is an <code>Option</code> that can hold a reference to a <code>String</code> (<code>&amp;String</code>) or <code>None</code>. The <code>&amp;String</code> inside <code>Option&lt;&amp;String&gt;</code> is a borrowed reference, meaning it does not have ownership of the data, and it cannot be modified or moved. It points to an existing <code>String</code> owned elsewhere.</p>
<p>Either we can change the definition of our struct and use <code>Option&lt;&amp;String&gt;</code> then we have to make sure about the borrowing and life of the referred string. Or we can clone the string as per our use case.</p>
<pre><code class="lang-rust">style : <span class="hljs-built_in">Option</span>::from(<span class="hljs-built_in">String</span>::from(data.style.as_ref()
        .unwrap_or(&amp;<span class="hljs-string">"European"</span>.to_string())))
</code></pre>
<p><code>.unwrap_or(&amp;"European".to_string())</code> is used to provide a default value in case the <code>Option</code> is <code>None</code>. If the <code>data.style</code> is <code>Some(String)</code>, this part is ignored. If the <code>data.style</code> was <code>None</code>, it creates a new <code>String</code> with the value <code>"European"</code> and returns a reference to it. Note <code>unwrap_or</code> expect <code>&amp;String</code> hence we return a reference <code>&amp;</code> .</p>
<p>Here is youtube video discuss about the Option&lt;&amp;T&gt; and &amp;Option&lt;T&gt;</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/6c7pZYP_iIE?si=j4XuPseEopJ-RVey">https://youtu.be/6c7pZYP_iIE?si=j4XuPseEopJ-RVey</a></div>
<p> </p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, you typically use <code>Option</code> in Rust represents optional or nullable value and wants to avoid null pointer errors and ensure safer code. You most often use when:</p>
<ul>
<li><p>You expect a function to return a value but it might fail or return nothing, you use <code>Option</code> to handle the result.</p>
</li>
<li><p>You have a variable that might be initialized with a valid value or remain uninitialized, you use <code>Option</code> to represent its state.</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Multithreading in Rust for Algorithmic Trading]]></title><description><![CDATA[In algorithmic trading, speed, correctness and efficiency are paramount, and utilizing multithreading can significantly enhance the performance of trading systems. Rust, with its focus on safety, concurrency, and performance, provides a powerful lang...]]></description><link>https://siddharthqs.com/multithreading-in-rust-for-algorithmic-trading</link><guid isPermaLink="true">https://siddharthqs.com/multithreading-in-rust-for-algorithmic-trading</guid><category><![CDATA[Rust]]></category><category><![CDATA[multithreading]]></category><category><![CDATA[algotrading]]></category><category><![CDATA[algorithmic trading]]></category><dc:creator><![CDATA[Siddharth]]></dc:creator><pubDate>Wed, 24 May 2023 01:46:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1684886305195/6629cef6-7610-4c42-80f2-60970689c343.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In algorithmic trading, speed, correctness and efficiency are paramount, and utilizing multithreading can significantly enhance the performance of trading systems. Rust, with its focus on safety, concurrency, and performance, provides a powerful language for building high-performance trading systems. Rust's ownership and borrowing system helps enforce thread safety at compile time. In this article, we will see multithreading in Rust in the context of an algorithmic trading application. Multiple threads can process market data concurrently, enabling faster signal generation and ultimately reducing the latency and increasing the overall throughput of the trading system. Trading systems can be extremely complex however on a high level, it has three components.</p>
<ul>
<li><p><strong><em>Market data feed</em></strong>: Simulated or real-time market data stream.</p>
</li>
<li><p><strong><em>Signal generation</em></strong>: Analysis of market data to generate trading signals.</p>
</li>
<li><p><strong><em>Order execution</em></strong>: Placement and execution of trading orders.</p>
</li>
</ul>
<p>In a simple example of this system, we need at least three separate threads to handle simulating market data, signal generation, and order execution, allowing the trading system to react swiftly to market conditions.</p>
<h2 id="heading-market-data-simulation">Market Data Simulation</h2>
<p>For the sake of simplicity for this blog, let's just simulate a single stock. A common way to represent an order book is by using a struct. Here's an example of a basic struct for an order book:</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[derive(Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Quote</span></span> {
    symbol: <span class="hljs-built_in">String</span>,
    bids: (<span class="hljs-built_in">f64</span>, <span class="hljs-built_in">u32</span>),
    asks: (<span class="hljs-built_in">f64</span>, <span class="hljs-built_in">u32</span>),
}
<span class="hljs-meta">#[derive(Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Order</span></span> {
    symbol: <span class="hljs-built_in">String</span>,
    quantity: <span class="hljs-built_in">i32</span>,
    price: <span class="hljs-built_in">f64</span>,
    order_type: <span class="hljs-built_in">String</span>,
}
</code></pre>
<p>In this example, the <code>Quote</code> struct has fields: <code>bids</code> and <code>asks</code>. Each field holds tuples representing the best price levels and quantities. You can further enhance the <code>Quote</code> to hold the vector for bids and asks e.g. <code>bids: Vec&lt;(f64, u32)&gt;</code>.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">simulate_market_data</span></span>() -&gt; Quote {
    <span class="hljs-keyword">let</span> normal = rand_distr::Normal::new(<span class="hljs-number">0.0</span>, <span class="hljs-number">1.0</span>).unwrap();
    <span class="hljs-keyword">let</span> z = normal.sample(&amp;<span class="hljs-keyword">mut</span> rand::thread_rng());
    <span class="hljs-keyword">let</span> st = <span class="hljs-number">100.0</span>;
    <span class="hljs-keyword">let</span> risk_free_rate = <span class="hljs-number">0.05</span>;
    <span class="hljs-keyword">let</span> volatility = <span class="hljs-number">0.2</span>;
    <span class="hljs-keyword">let</span> dt = <span class="hljs-number">1.0</span>/<span class="hljs-number">252.0</span>;
    <span class="hljs-keyword">let</span> bidprice = st*exp(((risk_free_rate - <span class="hljs-number">0.5</span> * volatility.powi(<span class="hljs-number">2</span>)) * dt)+volatility * dt.sqrt()*z);
    <span class="hljs-keyword">let</span> askprice = bidprice + <span class="hljs-number">0.05</span>;
    <span class="hljs-comment">// Generate random quantity</span>
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> rng = rand::thread_rng();
    <span class="hljs-keyword">let</span> bid_quantity = rng.gen_range(<span class="hljs-number">100</span>..<span class="hljs-number">1000</span>);
    <span class="hljs-keyword">let</span> ask_quantity = rng.gen_range(<span class="hljs-number">100</span>..<span class="hljs-number">1000</span>);
    <span class="hljs-keyword">let</span> quote = OrderBook {
        symbol: <span class="hljs-string">"SPY"</span>.to_string(),
        bids: (bidprice, bid_quantity),
        asks: (askprice, ask_quantity),
    };
    <span class="hljs-keyword">return</span> quote
}
</code></pre>
<p>In this example, the <code>simulate_market_data</code> function generates random market data and returns Quote.</p>
<h2 id="heading-channels-for-inter-thread-communication">Channels for inter-thread communication</h2>
<p>Channel provides a built-in communication mechanism for inter-thread data exchange. It handles synchronization internally, reducing the likelihood of synchronization errors.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">market_data</span></span>(tx: mpsc::Sender&lt;Quote&gt;) {
    <span class="hljs-keyword">loop</span> {
        <span class="hljs-comment">// Generate market data</span>
        <span class="hljs-keyword">let</span> order_data = simulate_market_data();
        <span class="hljs-comment">// Send market data to the main thread</span>
        tx.send(order_data).expect(<span class="hljs-string">"Failed to send market data"</span>);
        <span class="hljs-comment">// Pause the execution for one millisecond</span>
        thread::sleep(Duration::from_millis(<span class="hljs-number">1</span>));
    }
}
</code></pre>
<p>We will run the <code>market_data</code> function in a separate thread and repeatedly generates market data using <code>simulate_market_data</code>. It sends the generated market data to the main thread via a channel (<code>tx</code>) and wait for one millisecond to send another order data.</p>
<h2 id="heading-spawn-threads">Spawn threads</h2>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-comment">// Create channels for inter-thread communication</span>
    <span class="hljs-keyword">let</span> (tx, rx) = mpsc::channel();
    <span class="hljs-keyword">let</span> (tx_order, rx_order) = mpsc::channel();
    <span class="hljs-comment">// Spawn a thread for market data simulation</span>
    thread::spawn(<span class="hljs-keyword">move</span> || {
        market_data(tx);
    });
    <span class="hljs-comment">// Receive and process market data in the separate thread</span>
    thread::spawn(<span class="hljs-keyword">move</span> || {
        signal_generation(rx,tx_order);
    });
    thread::spawn(<span class="hljs-keyword">move</span> || {
        order_management(rx_order);
    });
    <span class="hljs-keyword">loop</span>{}
}
</code></pre>
<p>In the <code>main</code> function, two channels are created for inter-thread communication using <code>mpsc::channel()</code>. Then, three separate threads are spawned using <code>thread::spawn</code>, where the <code>market_data, signal_generation and order_management</code> functions are executed. The main thread continuously receives market data from the channel using <code>rx.recv()</code>. Upon receiving market data, it can process it according to the requirements.</p>
<h2 id="heading-signal-generation-and-order-management">Signal generation and order management</h2>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">signal_generation</span></span>(rx: mpsc::Receiver&lt;Quote&gt;,tx_order: mpsc::Sender&lt;Order&gt;){
    <span class="hljs-keyword">while</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Ok</span>(data) = rx.recv() {
        <span class="hljs-comment">// Process market data</span>
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Received market data: {:?}"</span>, data);
        <span class="hljs-keyword">let</span> bid_price = data.bids.<span class="hljs-number">0</span>;
        <span class="hljs-keyword">let</span> ask_price = data.asks.<span class="hljs-number">0</span>;
        <span class="hljs-keyword">if</span> bid_price&lt;<span class="hljs-number">100.0</span>{
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Place BUY Order"</span>);
            <span class="hljs-keyword">let</span> order = Order {
                symbol: data.symbol,
                quantity: <span class="hljs-number">1</span>,
                price: bid_price,
                order_type: <span class="hljs-string">"LMT"</span>.to_string(),
            };
            tx_order.send(order).expect(<span class="hljs-string">"Failed to send order"</span>);
        }
        <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> ask_price&gt;<span class="hljs-number">100.0</span> {
            <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Place SELL Order"</span>);
            <span class="hljs-keyword">let</span> order = Order {
                symbol: data.symbol,
                quantity: <span class="hljs-number">1</span>,
                price: ask_price,
                order_type: <span class="hljs-string">"LMT"</span>.to_string(),
            };
            tx_order.send(order).expect(<span class="hljs-string">"Failed to send order"</span>);
        };
    }
}
</code></pre>
<p>Here we are using two channels one for receiving Quotes and another for sending orders.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">order_management</span></span>(rx:mpsc::Receiver&lt;Order&gt;){
    <span class="hljs-keyword">while</span> <span class="hljs-keyword">let</span> <span class="hljs-literal">Ok</span>(data) = rx.recv() {
        <span class="hljs-comment">// Process Orders</span>
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"Received order: {:?}"</span>, data);
    }
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684891751971/71ee1476-f4af-44d1-bc3c-1c5388cb1251.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-other-considerations">Other considerations</h2>
<p>You can use Mutex as well. Ideally, use mutexes to protect shared data and coordinate access to critical sections. You may have multi-step operations that involve multiple threads collaborating to complete a task then Mutexes can be used to coordinate the execution of these operations, ensuring that threads wait for their turn and follow a specific order or synchronization protocol.</p>
<p>Additionally, other synchronization primitives like RwLock, Atomic types, or even higher-level abstractions like message queues or publish-subscribe systems are useful depending on the specific requirements.</p>
<h2 id="heading-resources">Resources</h2>
<p>Here is an excellent video by <a target="_blank" href="https://www.youtube.com/@jonhoo"><strong>Jon Gjengset</strong></a> to learn more about channels.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/b4mS5UPHh20">https://youtu.be/b4mS5UPHh20</a></div>
<p> </p>
<p>And here is another great resource to learn multithreading in Rust, probably the <strong>BEST Book on concurrency</strong> by Mara Bos. Excellent Read. Thank you, Mara.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://read.amazon.com/kp/embed?asin=B0BQ5LN9KC&amp;preview=newtab&amp;linkCode=kpe&amp;ref_=cm_sw_r_kb_dp_R690WMZJP7WC9SWHKS2X">https://read.amazon.com/kp/embed?asin=B0BQ5LN9KC&amp;preview=newtab&amp;linkCode=kpe&amp;ref_=cm_sw_r_kb_dp_R690WMZJP7WC9SWHKS2X</a></div>
<p> </p>
<p>There are a few Rust-specific tools like <a target="_blank" href="https://github.com/flamegraph-rs/flamegraph"><code>flamegraph</code></a> that can help identify bottlenecks and areas for optimization while using multithreading. Flamegraphs are used to visualize where time is being spent.</p>
<p>Hope this is helpful!</p>
]]></content:encoded></item><item><title><![CDATA[Demystifying Order Execution Algorithms in Trading: Part 1 - Understanding TWAP]]></title><description><![CDATA[Often when we hear algorithmic trading, we think about alpha-seeking algorithms i.e. generating profits by predicting market movements or identifying mispricings or trends and executing trades automatically. However, for a long time, algorithmic trad...]]></description><link>https://siddharthqs.com/demystifying-order-execution-algorithms-in-trading-part-1-understanding-twap</link><guid isPermaLink="true">https://siddharthqs.com/demystifying-order-execution-algorithms-in-trading-part-1-understanding-twap</guid><category><![CDATA[trading, ]]></category><category><![CDATA[algotrading]]></category><category><![CDATA[algorithmic trading]]></category><category><![CDATA[stockmarket]]></category><category><![CDATA[Rust]]></category><dc:creator><![CDATA[Siddharth]]></dc:creator><pubDate>Fri, 05 May 2023 06:11:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1683266930905/5973e143-53ec-4b37-8145-c4f15ebb3844.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Often when we hear algorithmic trading, we think about alpha-seeking algorithms i.e. generating profits by predicting market movements or identifying mispricings or trends and executing trades automatically. However, for a long time, algorithmic trading was synonymous with execution algorithms, these are a type of trading algorithm that is designed to execute trades in a way that minimizes market impact and transaction costs. They are used by institutional investors and traders to manage large orders and execute trades more efficiently than traditional manual methods. Suppose you aim to sell one million shares of Apple; you cannot simply place a single market order for one million shares as it could cause a market crash. Common sense says you should divide the order into ten or hundreds of suborders for execution. However, executing these suborders is complex and nuanced and warrants serious consideration like <strong><em>trading rate</em></strong> (The rate at which traders execute an order) and <strong><em>order type</em></strong> (market order or limit order). In this blog, we will delve into the details of the <strong><em>time-weighted average price (TWAP)</em></strong>, the most common and fundamental execution algorithm.</p>
<h2 id="heading-time-weighted-average-price-twap-algorithm">Time-weighted Average Price (TWAP) Algorithm</h2>
<p>TWAP algorithms are designed to execute trades based on a rate proposed to time. As an example, suppose you want to purchase 5000 shares of AAPL over a period of 10 minutes. By using TWAP, you would buy 500 shares during the first minute, followed by another 500 shares during the next minute, and so on. By the beginning of the 10th minute, you should have already bought 4500 shares (90%) and started buying the rest. The process is relatively simple: you create a schedule of 10 orders, and send them at appropriate intervals (e.g. every minute). This can be easily achieved by sending market orders. Let's examine the code to gain a better understanding. In the code below, "total_time" refers to the overall duration of the order, and "interval" refers to the time between each execution interval. By passing the interval as 1, we indicate that the execution should occur every minute.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::thread;
<span class="hljs-keyword">use</span> std::time::Duration;

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">twap</span></span>(symbol: <span class="hljs-built_in">String</span>, quantity: <span class="hljs-built_in">i32</span>,total_time:<span class="hljs-built_in">i32</span> interval: <span class="hljs-built_in">i32</span>,orderType: <span class="hljs-built_in">String</span>) {
    <span class="hljs-comment">// Calculate the number of sub-orders needed</span>
    <span class="hljs-keyword">let</span> num_orders = total_time / interval;
    <span class="hljs-comment">// Calculate the quantity for each sub-order</span>
    <span class="hljs-keyword">let</span> sub_order_quantity = quantity / num_orders;
    <span class="hljs-comment">// Send the sub-orders at regular intervals</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-number">1</span>..=num_orders {
        send_order(ticker,sub_order_quantity,orderType);
        thread::sleep(Duration::from_secs(interval*<span class="hljs-number">60</span> <span class="hljs-keyword">as</span> <span class="hljs-built_in">u64</span>));
    }
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    twap(<span class="hljs-symbol">'AAPL</span>',<span class="hljs-number">5000</span>, <span class="hljs-number">10</span>,<span class="hljs-number">1</span>,<span class="hljs-symbol">'MKT</span>');
}
</code></pre>
<p>To maintain the schedule, I opted to use market orders. Market orders allow for immediate buying or selling of securities at the prevailing market price. However, this comes at a cost, as market orders often have higher fees and less favorable prices. Despite being able to achieve the desired trading rate of 500 shares per minute, this approach results in the worst possible execution. Another option to consider is using a Limit Order, where a trader sets a price at which they are willing to buy or sell an asset. The order is then only executed when the market price reaches the specified price or a better one. However, there is no guarantee that a limit order will be executed.</p>
<p>Using limit orders in the TWAP may lead to a situation where a significant number of orders, including large quantities, are left unexecuted, causing a deviation from the desired schedule. Here is the trade-off between market order and limit order, the optimal implementation of TWAP requires both order-type.</p>
<p>It is common to establish acceptable ranges within which the algorithm can deviate from the desired schedule. These ranges define upper and lower limits on the number of shares that the algorithm is permitted to be ahead of or behind schedule at any given point.</p>
<p>Let's consider a range of 10% deviation from the desired schedule, e.g. we are allowed to deviate by 10 % of quantity at a given point in time. In our example at 2 minutes, we should execute 20% of the quantity (1000 shares)), however, we are allowed to deviate 10% so we can have only 10% (500 shares not less). We can start placing limit orders according to our schedule and if our order doesn't get executed and the deviation threshold is breached, we can modify the order type to a market order. <strong><em>A minimum quantity must be executed</em></strong>. Similarly, we have the maximum quantity from the upper bound, the difference between the maximum and minimum quantity is called <strong><em>"maximum working quantity".</em></strong> The maximum working quantity in our case is 1000 shares, it is the key consideration to decide the upper and lower bound along with asset liquidity.</p>
<p>Let's improve our code above a bit.</p>
<p>To implement the algorithm we discussed above, we have two threads. One thread places the order according to the schedule (twap) and the other thread keeps checking pending orders and changes the order type to market and send the order.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">use</span> std::sync::{Arc, Mutex};
<span class="hljs-keyword">use</span> std::time::Duration;
<span class="hljs-keyword">use</span> std::thread;
<span class="hljs-meta">#[derive(Debug)]</span>
<span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Order</span></span> {
    symbol: <span class="hljs-built_in">String</span>,
    quantity: <span class="hljs-built_in">i32</span>,
    price: <span class="hljs-built_in">f64</span>,
    order_type: <span class="hljs-built_in">String</span>,
    status: <span class="hljs-built_in">String</span>
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">twap</span></span>(symbol: <span class="hljs-built_in">String</span>, quantity: <span class="hljs-built_in">i32</span>,total_time:<span class="hljs-built_in">i32</span>, interval: <span class="hljs-built_in">i32</span>, order_book_clone:&amp;Arc&lt;Mutex&lt;<span class="hljs-built_in">Vec</span>&lt;Order&gt;&gt;&gt; ) {
    <span class="hljs-comment">//let order_book_clone = Arc::clone(&amp;order_book);</span>
    <span class="hljs-keyword">let</span> num_orders = total_time / interval;

    <span class="hljs-keyword">let</span> sub_order_quantity = quantity / num_orders;
    <span class="hljs-comment">// Send the sub-orders at regular intervals</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-number">1</span>..=num_orders {
        <span class="hljs-keyword">let</span> order = Order{
            symbol : symbol.clone(),
            quantity: sub_order_quantity,
            price: <span class="hljs-number">0.0</span>,
            order_type: <span class="hljs-built_in">String</span>::from(<span class="hljs-string">"LMT"</span>),
            status: 
            };
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> order_book = order_book_clone.lock().unwrap();
        send_order(&amp;order)
        order_book.push(order);
        <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, order_book);
        thread::sleep(Duration::from_secs(interval <span class="hljs-keyword">as</span> <span class="hljs-built_in">u64</span>));
    }
}

<span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">main</span></span>() {
    <span class="hljs-comment">// Create a shared order book</span>
    <span class="hljs-keyword">let</span> order_book = Arc::new(Mutex::new(<span class="hljs-built_in">Vec</span>::&lt;Order&gt;::new()));

    <span class="hljs-comment">// Clone the order book for use in the threads</span>
    <span class="hljs-keyword">let</span> order_book_clone = Arc::clone(&amp;order_book);

    <span class="hljs-comment">// Thread to place orders</span>
    <span class="hljs-keyword">let</span> place_order_thread = thread::spawn(<span class="hljs-keyword">move</span> || twap(<span class="hljs-string">"AAPL"</span>.to_string(),<span class="hljs-number">5000</span>, <span class="hljs-number">10</span>,<span class="hljs-number">1</span>,&amp;order_book_clone));

    <span class="hljs-comment">// Clone the order book again for use in the threads</span>
    <span class="hljs-keyword">let</span> order_book_clone = Arc::clone(&amp;order_book);

    <span class="hljs-comment">// Thread to observe and change orders</span>
    <span class="hljs-keyword">let</span> observe_order_thread = thread::spawn(<span class="hljs-keyword">move</span> || {
        <span class="hljs-keyword">loop</span> {
            thread::sleep(Duration::from_secs(interval <span class="hljs-keyword">as</span> <span class="hljs-built_in">u64</span>));
            <span class="hljs-comment">// Lock the order book and observe the orders</span>
            <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> order_book = order_book_clone.lock().unwrap();
            <span class="hljs-comment">// Check if there are any orders with status "PENDING"</span>
            <span class="hljs-keyword">let</span> pending_orders = order_book
                .iter_mut()
                .filter(|order| order.status == <span class="hljs-string">"PENDING"</span>)
                .collect::&lt;<span class="hljs-built_in">Vec</span>&lt;_&gt;&gt;();
            <span class="hljs-keyword">for</span> order <span class="hljs-keyword">in</span> pending_orders {
                order.order_type = '<span class="hljs-string">"MKT"</span>
                send_order(&amp;order);
            } 
        }
    });

    <span class="hljs-comment">// Wait for the threads to finish</span>
    place_order_thread.join().unwrap();
    observe_order_thread.join().unwrap();
}
</code></pre>
<p>It is crucial that we promptly identify and rectify any deviation from the upper and lower bounds by implementing necessary changes and minimizing tracking errors. In addition, there are various proprietary implementations of TWAP, some of which integrate other algorithms such as VMAP to improve execution.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>TWAP is considered to be a fundamental and indispensable execution algorithm. It is a simple and effective strategy that evenly distributes trading volume over a specific period to minimize market impact. It is important to have a clear understanding of TWAP, as it forms the basis for other more complex execution algorithms used in trading. By understanding TWAP, one can gain insights into other popular execution algorithms such as VWAP, POV, and IS. These algorithms have become essential tools in modern trading, enabling traders to execute large orders with minimal market impact. In conclusion, it is worth investing time and effort to learn the fundamentals of TWAP.</p>
]]></content:encoded></item><item><title><![CDATA[Introduction to TimescaleDB for Algorithmic Trading]]></title><description><![CDATA[In algorithmic trading, you often retrieve data once from web services (data provider) and use it multiple times to back-test multiple strategies. The tick data is used again and again hundreds of times for different transformations (like aggregation...]]></description><link>https://siddharthqs.com/introduction-to-timescaledb-for-algorithmic-trading</link><guid isPermaLink="true">https://siddharthqs.com/introduction-to-timescaledb-for-algorithmic-trading</guid><category><![CDATA[time-series-database]]></category><category><![CDATA[time series]]></category><category><![CDATA[trading, ]]></category><dc:creator><![CDATA[Siddharth]]></dc:creator><pubDate>Wed, 05 Apr 2023 01:52:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680641814852/a4fb6353-5295-4d62-91b4-c553d556fbee.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In algorithmic trading, you often retrieve data once from web services (data provider) and use it multiple times to back-test multiple strategies. The tick data is used again and again hundreds of times for different transformations (like aggregations, creating candles in real time) in backtesting of trading strategies You can obviously store in-memory data on disk in CSV format however as data grow, you need a database to cut out a significant amount of latency. As the nature of data requires almost no update, only Insert and Select statements multiple times, we should use a database that is optimized for this purpose. Here comes the time series databases.</p>
<h2 id="heading-what-is-a-time-series-database">What is a time series database?</h2>
<p>A time series database (TSDB) is a database optimized for storing and serving time series data. Time series data is data that is collected over time, such as financial market data, logs, monitoring data, and weather data. TSDBs are designed to make it easy to store, query, and analyze time series data.</p>
<h2 id="heading-examples-of-time-series-databases">Examples of Time series databases</h2>
<ul>
<li><p><strong>InfluxDB:</strong> InfluxDB is an open-source time series database that is designed for high performance and scalability. It is used by a variety of organizations, including Uber, Twitch, and Yelp.</p>
</li>
<li><p><strong>Prometheus:</strong> Prometheus is an open-source monitoring system and time series database that is used by a variety of organizations, including Google, Facebook, and Netflix.</p>
</li>
<li><p><strong>TimescaleDB:</strong> TimescaleDB is an open-source time series database that is based on PostgreSQL. It provides the performance and scalability of a traditional database with the flexibility and features of a time series database.</p>
</li>
<li><p><strong>DolphinDB:</strong> DolphinDB is a commercial time series database that is designed for high performance and scalability. It is used by a variety of organizations, including Goldman Sachs, Morgan Stanley, and IBM.</p>
</li>
<li><p><strong>RRDTool:</strong> RRDTool is an open-source tool for storing and graphing time series data. It is often used for monitoring systems and network traffic analysis.</p>
</li>
<li><p><strong>OpenTSDB:</strong> OpenTSDB is an open-source time series database that is based on HBase. It is used by a variety of organizations, including Twitter, Facebook, and Yahoo.</p>
</li>
</ul>
<h2 id="heading-timescaledb-postgres-for-time-series">TimescaleDB: <strong>Postgres for time-series</strong></h2>
<p>TimescaleDB is an open-source relational database that extends PostgreSQL with time-series capabilities. TimescaleDB allows developers and organizations to store, query, and analyze time-series data at scale. It also includes features such as automatic data partitioning, advanced indexing for time-series queries, and support for SQL and native time-series functions.</p>
<h2 id="heading-how-to-install-timescale-db">How to install Timescale DB?</h2>
<p>The easiest way is to install using Docker. If you are using Windows, you need to install the docker desktop that would get installed in System Drive (C drive). It will create 2 distros docker-desktop and docker-desktop-data. You can see this at <code>%LOCALAPPDATA%/Docker/wsl</code>; and inside you will find <strong>vhdx</strong> file. If you are running low on System drive space, you can move docker-desktop-data out to another drive.</p>
<pre><code class="lang-powershell">wsl -<span class="hljs-literal">-shutdown</span>
wsl -<span class="hljs-literal">-export</span> docker<span class="hljs-literal">-desktop</span><span class="hljs-literal">-data</span> D:\docker<span class="hljs-literal">-desktop</span>\docker<span class="hljs-literal">-desktop</span><span class="hljs-literal">-data</span>.tar
wsl -<span class="hljs-literal">-unregister</span> docker<span class="hljs-literal">-desktop</span><span class="hljs-literal">-data</span>
wsl -<span class="hljs-literal">-import</span> docker<span class="hljs-literal">-desktop</span><span class="hljs-literal">-data</span> D:\docker<span class="hljs-literal">-desktop</span>\data D:\docker<span class="hljs-literal">-desktop</span>\docker<span class="hljs-literal">-desktop</span><span class="hljs-literal">-data</span>.tar -<span class="hljs-literal">-version</span> <span class="hljs-number">2</span>
</code></pre>
<p>More detail on this can be found on this <a target="_blank" href="https://dev.to/kimcuonthenet/move-docker-desktop-data-distro-out-of-system-drive-4cg2">page.</a></p>
<p>You can install a TimescaleDB instance from a pre-built container.</p>
<ul>
<li><p>Run the docker image: The TimescaleDB HA Docker image includes <a target="_blank" href="https://ubuntu.com/"><strong>Ubuntu</strong></a> as its operating system.</p>
<pre><code class="lang-powershell">  docker pull timescale/timescaledb<span class="hljs-literal">-ha</span>:pg14<span class="hljs-literal">-latest</span>
</code></pre>
</li>
<li><p>Run the image from the container</p>
<pre><code class="lang-powershell">  docker run <span class="hljs-literal">-d</span> -<span class="hljs-literal">-name</span> timescaledb <span class="hljs-literal">-p</span> <span class="hljs-number">5432</span>:<span class="hljs-number">5432</span> <span class="hljs-literal">-e</span> POSTGRES_PASSWORD=password timescale/timescaledb<span class="hljs-literal">-ha</span>:pg14<span class="hljs-literal">-latest</span>
</code></pre>
</li>
<li><pre><code class="lang-plaintext">    docker start timescaledb # To start docker container
    docker stop timescaledb # To stop docker container
</code></pre>
</li>
</ul>
<p>You can use pgAdmin to connect to this container and create tables accordingly.</p>
<ul>
<li>Install / Open pgAdmin and add a new server</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680639291835/ce7b341b-8f1f-4218-8992-4739dbea74db.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p>Provide the hostname, port, database, username and password to connect to the instance running on the docker container.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680639393933/a73fb8ce-9508-461e-958d-c4397aa82897.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>You can just use SQL queries like creating a table by executing the SQL query below. You don't need to learn any other structured query language to work with Timescaledb, unlike Influxdb.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680639637748/e0f64522-e6ea-4764-a484-aa5ec0fc0aa8.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<p>However, we will of course use Python to connect with Timescaledb using psycopg2 and sqlalchemy.</p>
<h2 id="heading-connect-from-python-using-psycopg2">Connect from Python using Psycopg2</h2>
<p>Psycopg2 is the most loved PostgreSQL database adapter for Python, hence worked with TimescaleDB. It was designed for heavily multi-threaded applications that create and destroy lots of cursors and make a large number of concurrent “INSERT”s or “UPDATE”s.</p>
<pre><code class="lang-powershell">pip install psycopg2<span class="hljs-literal">-binary</span>
</code></pre>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> psycopg2
<span class="hljs-comment"># Create connection</span>
con = psycopg2.connect(
                host = <span class="hljs-string">'hostname'</span>
                database =<span class="hljs-string">'dbname'</span>,
                user = <span class="hljs-string">'postgres'</span>,
                password = <span class="hljs-string">'password'</span>)
<span class="hljs-comment"># Create cursor</span>
cur = con.cursor()
<span class="hljs-comment"># SQL</span>
query = <span class="hljs-string">'INSERT INTO stock_intraday (time,symbol,price_open,price_close,
        price_low,price_high,trading_volume VALUES (%s,%s,%s,%s,%s,%s,%s)'</span>
record =(time,symbol,price_open,price_close,
        price_low,price_high,trading_volume)
cur.execute(query,record)
<span class="hljs-comment">#commit</span>
con.commit()
<span class="hljs-comment">#close the connection</span>
con.close()
</code></pre>
<h2 id="heading-ingest-pandas-dataframe-to-timescaledb">Ingest Pandas Dataframe to TimescaleDB</h2>
<p>There are multiple ways to ingest data into our database, however, I want to discuss quickly the simplest and probably the slowest using sqlalchemy. Let's say you have a DataFrame df as below. We can create and insert DataFrame using to_sql:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680650086643/f40d520c-901f-4cb8-8ebf-c35cb7ab1734.png" alt class="image--center mx-auto" /></p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> sqlalchemy <span class="hljs-keyword">import</span> create_engine
engine = create_engine(<span class="hljs-string">'postgresql://postgres:pwd@localhost:5432/postgres'</span>)
df.to_sql(<span class="hljs-string">'abc'</span>, con=engine, if_exists = <span class="hljs-string">'replace'</span>,index =<span class="hljs-literal">True</span>)
</code></pre>
<p>A table gets created based on the data frame with the datatype supported by TimescaleDB.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680650310441/6022295c-3470-452a-8105-98d7593059c1.png" alt class="image--center mx-auto" /></p>
<pre><code class="lang-python"><span class="hljs-comment"># reading the table from the db</span>
query = <span class="hljs-string">"SELECT * FROM "</span> + table_name
df = pd.read_sql_query(query, engine)
</code></pre>
<h2 id="heading-features-of-timescaledb">Features of TimescaleDB</h2>
<p>At least these feature two worth mentioning here:</p>
<h3 id="heading-hypertables">Hypertables</h3>
<p>Hypertables are PostgreSQL tables that automatically partition your data by time. With hypertables, Timescale makes it easy to improve insert and query performance by partitioning time-series data on its time parameter. Behind the scenes, the database performs the work of setting up and maintaining the hypertable's partitions. Each hypertable is made up of child tables called chunks. Each chunk is assigned a range of time, and only contains data from that range.</p>
<p><a target="_blank" href="https://docs.timescale.com/use-timescale/latest/hypertables/about-hypertables/">More about hypertables</a></p>
<h3 id="heading-continuous-aggregates"><strong>Continuous aggregates</strong></h3>
<p>If you are collecting tick data, e.g. several stock prices per seconds, you might want to aggregate your data into 1 minute, 5 minute or 1-hour instead, with open, close, high, and low candles. Continuous aggregates take raw tick data from the original hypertable, aggregate it, and store the intermediate state in a materialization hypertable. Continuous aggregate views are refreshed automatically in the background as new data is added. Timescale tracks these changes to the dataset and automatically updates the view in the background.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>While working with stock data, you can store it in flat files such as CSV, HDFStore object or SQLite. As you start working with thousands of stock prices and with multi-year data (e.g. 5 mins or 15 mins candles) you need to store the time series in the databases. You can transfer several calculations and transformations to the server side where it is most suited. TimescaleDB is the natural choice as it is open source, an extension of PostgreSQL, and supports SQL with native support for time series.</p>
<p>Happy Trading!</p>
]]></content:encoded></item><item><title><![CDATA[Sharing My AWS (AMAZON WEB SERVICES) Notes]]></title><description><![CDATA[Welcome to my notes on AWS. I hope that sharing them, will help you quickly get an introduction or act as a refresher while you navigate the labyrinth of AWS. I started with watching a few youtube videos and, for me, youtube videos are too time-consu...]]></description><link>https://siddharthqs.com/my-aws-notes</link><guid isPermaLink="true">https://siddharthqs.com/my-aws-notes</guid><category><![CDATA[AWS]]></category><category><![CDATA[AWS Certified Developer - Associate]]></category><category><![CDATA[AWS Certified Solutions Architect Associate]]></category><category><![CDATA[aws lambda]]></category><category><![CDATA[Cloud]]></category><dc:creator><![CDATA[Siddharth]]></dc:creator><pubDate>Mon, 16 Jan 2023 07:11:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1673848488680/3bc4ae6f-6b59-4aa1-b1f1-5067fe97e3fa.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to my notes on AWS. I hope that sharing them, will help you quickly get an introduction or act as a refresher while you navigate the labyrinth of AWS. I started with watching a few youtube videos and, for me, youtube videos are too time-consuming and can be frustrating to watch twice, especially when you are short on time and just want to get the information you need. So these notes I took a year ago to save myself from endless videos when I started looking into AWS and considered AWS certifications.</p>
<p>Here you will not find a well-written blog on how to AWS, instead raw badly written notes on various services. I invite you to add your notes on more services or suggestions. Here we go:</p>
<h2 id="heading-services-provided-by-amazon"><strong>SERVICES PROVIDED BY AMAZON:</strong></h2>
<h3 id="heading-networking-andamp-content-delivery"><strong>NETWORKING &amp; CONTENT DELIVERY:</strong></h3>
<p>Lambda, EC2, VPC, Route53</p>
<h3 id="heading-storage"><strong>STORAGE:</strong></h3>
<p>S3 (Simple storage service), Glacier, EFS (Elastic File service), Storage Gateway</p>
<h3 id="heading-databases"><strong>DATABASES:</strong></h3>
<p>RDS (Relational Database Service), DynamoDB, Redshift, Elasticache</p>
<h3 id="heading-migration"><strong>MIGRATION:</strong></h3>
<p>Snowball, DMS (Database migration services), SMS (Server Migration Service)</p>
<h3 id="heading-analytics"><strong>ANALYTICS:</strong></h3>
<p>Athena, EMR (Elastic Map Reduce), Cloud Search, Elastic Search, Kinesis, Data Pipeline</p>
<h3 id="heading-security-andamp-identity"><strong>SECURITY &amp; IDENTITY:</strong></h3>
<p>IAM (Identity Access Management), Inspector, Certificate Manager, Directory Service, WAF (Web Application Firewall), Artifacts</p>
<h3 id="heading-management-tools"><strong>MANAGEMENT TOOLS:</strong></h3>
<p>Cloud Watch, Cloud Formation, Cloud Trail, Opsworks, Config, Service Catalog, Trusted Advisor</p>
<h3 id="heading-iam-identity-access-management"><strong>IAM (IDENTITY ACCESS MANAGEMENT)</strong></h3>
<p>IAM allows you to manage users and their level of access to the AWS Console.</p>
<p>IAM gives you:</p>
<ul>
<li><p>Centralized control of AWS account.</p>
</li>
<li><p>Shared access to your AWS account.</p>
</li>
<li><p>Granular Permission means enabling different levels of access to different users within the organization.</p>
</li>
<li><p>Identity Federation (including Active Directory, FB, LinkedIn etc)</p>
</li>
<li><p>Multifactor Authentication- provides additional security for AWS account settings and resources.</p>
</li>
<li><p>Provide temporary access to users/devices, and services.</p>
</li>
</ul>
<p>IAM consists of the following:</p>
<ul>
<li><p>Users</p>
</li>
<li><p>Groups: Collection of users under one set of permission.</p>
</li>
<li><p>Roles: Used to define a set of permissions.</p>
</li>
<li><p>Policy Documents: Defines one or more permission, policies attached to a user, group or role.</p>
</li>
</ul>
<p><strong>Key Points</strong></p>
<ul>
<li><p><em>IAM is universal:</em> It doesn’t apply to regions.</p>
</li>
<li><p>The “root account” is simply the account created when you first set up your AWS account. It has complete Admin access.</p>
</li>
<li><p>New Users have no permission when first created.</p>
</li>
<li><p>New Users are assigned Access Key ID &amp; Secret Access Keys when first created.</p>
</li>
<li><p>These keys are not the same as a password, and you cannot use the Access Key ID &amp; Secret Access Key to log in to the AWS Management Console.</p>
</li>
<li><p>You can use this to access AWS via the APIs and Command Line Interface(CLI) from your local desktop.</p>
</li>
<li><p>You only get to view Access Key ID &amp; Secret Access Key once. If you lose them, you have to regenerate them, therefore, save them in a secure location.</p>
</li>
<li><p>Always set up Multifactor Authentication (MFA) on your root account.</p>
</li>
<li><p>You can create and customize your password rotation policies.</p>
</li>
</ul>
<h2 id="heading-serverless-computing"><strong>SERVERLESS COMPUTING</strong></h2>
<p>Serverless allows you to run application code in the cloud without worrying about managing any server. AWS handles the infrastructure management task so that you can focus on writing code. Management tasks handled by AWS are capacity provisioning, patching, Auto Scaling and High availability.</p>
<p><strong>Advantages of Serverless:</strong></p>
<ul>
<li><p>Speed to market (without managing infrastructure)</p>
</li>
<li><p>Super scalable.</p>
</li>
<li><p>Lower cost.</p>
</li>
<li><p>Focus on code only.</p>
</li>
</ul>
<h3 id="heading-lambda"><strong>LAMBDA</strong></h3>
<p><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT8gqqADEdwQ2jWvzsnAOOi5mbc076T-R37AQ&amp;usqp=CAU" alt="How the Serverless Framework is Reshaping AWS Lambda – The New Stack" class="image--center mx-auto" /></p>
<p>Lambda is a serverless computing service, which allows you to run your code without any AWS service. Supported Languages are Node.js, Java, Python, C#, Go, and Ruby.</p>
<p><strong>Lambda Pricing: Pricing is</strong> based on the number of requests, their duration and the amount of memory used by the Lambda function</p>
<ol>
<li><p>Number of requests: First 1 million requests are free. $0.02 per 1 million requests thereafter.</p>
</li>
<li><p>Duration**:** Charged in 1ms increment. This is calculated from the time your code begins executing until it returns or otherwise terminates, rounded up to the nearest 100ms.</p>
</li>
<li><p>Price per GB-second: The price depends on the amount of memory you allocate to your function. You are charged $ 0.00001667 for every GB-second used.</p>
</li>
</ol>
<p>Lambda is an <strong>Event-Driven and serverless application using</strong> an Event-Driven Architecture.</p>
<p>The lambda function can be automatically triggered by other AWS services or directly from any web or mobile app. These events could be changes made to data in S3 or DynamoDB table.</p>
<p>AWS services that can invoke Lambda functions are DynamoDB, Kinesis, SQS, Application Load Balancer, API Gateway, CloudFront, S3, SNS, SES, CloudFormation, CloudWatch, CLoudCommit, CloudPipeline etc.</p>
<p><strong>Key Points:</strong></p>
<ul>
<li><p>Cost-Effective</p>
</li>
<li><p>Continuous Scaling</p>
</li>
<li><p>Lambda function is independent: Each event will trigger a single function.</p>
</li>
<li><p>Event-Driven</p>
</li>
<li><p>Serverless Technology.</p>
</li>
</ul>
<p><strong>Version Control with Lambda:</strong></p>
<p><strong>Versioning:</strong> When versioning is used in AWS Lambda, you can publish one or more versions of your lambda function. As a result, you can work with different variations of your Lambda function in your development workflows, such as development, beta and production.</p>
<p>Each Lambda function version has a unique Amazon Resource Name (ARN). After you publish a version, it is immutable (that is it can’t be changed).</p>
<p>AWS Lambda maintains your function code in the $LATEST version. When you update your function code, AWS Lambda replaces the code in the $LATEST version of the Lambda function.</p>
<p><strong>Qualified/Unqualified ARNs</strong></p>
<ul>
<li><p>You can refer to this function using its ARN. There are two ARNs associated with this initial version:</p>
</li>
<li><p>Qualified ARN: The function ARN with the version suffix.</p>
</li>
</ul>
<p>arn:aws:lambda:aws-region:acct-id:function:helloworld:$LATEST</p>
<ul>
<li>Unqualified ARN: The function ARN without the version suffix.</li>
</ul>
<p>arn:aws:lambda:aws-region:acct-id:function:helloworld</p>
<p><strong>Key Points:</strong></p>
<ul>
<li><p>Can have multiple versions of lambda functions.</p>
</li>
<li><p>The latest version will use $latest.</p>
</li>
<li><p>The qualified version will use $latest, unqualified will not have it.</p>
</li>
<li><p>Versions are immutable.</p>
</li>
<li><p>Can split traffic using aliases to different versions.</p>
</li>
<li><p>Cannot split traffic with $latest, instead create an alias to latest.</p>
</li>
</ul>
<p><strong>Lambda Concurrent execution Limit:</strong></p>
<ul>
<li><p>The default concurrent execution limit is 1,000 per second.</p>
</li>
<li><p>Sometimes on serverless websites, websites hit the limit at some point.</p>
</li>
<li><p>If sites hit the limit then invocations are rejected-429 HTTP status code, which means there are too many requests.</p>
</li>
<li><p>The remedy is to get the limit raised by AWS support.</p>
</li>
</ul>
<h2 id="heading-ec2-elastic-compute-cloud">EC2 (<strong>ELASTIC COMPUTE CLOUD)</strong></h2>
<p><img src="https://svr474.a2cdn1.secureserver.net/wp-content/uploads/2021/10/image.png" alt class="image--center mx-auto" /></p>
<p>EC2 is secure, resizable compute capacity in the cloud.</p>
<ul>
<li><p>It’s like a virtual machine, only hosted in AWS instead of your own data center.</p>
</li>
<li><p>Designed to make web-scale cloud computing easier for developers.</p>
</li>
</ul>
<h4 id="heading-advantages"><strong>ADVANTAGES:</strong></h4>
<ul>
<li><p>Pay only for what you use.</p>
</li>
<li><p>No wasted capacity: Select the capacity you need and you can grow and shrink the capacity as per the requirements.</p>
</li>
</ul>
<p><strong>Pricing Options:</strong></p>
<ul>
<li><p>On-Demand: By default pricing option. Payment is done by the hour or the second depending on the type of instance you run. Low-cost pricing option.</p>
</li>
<li><p>Reserved: Reserved capacity for one or three years. These instances operate at a regional level.</p>
</li>
<li><p>Spot: Enables you to bid whatever price you want for instance capacity, providing even greater <em>savings</em> if your applications have flexible start and end times. Purchased unused capacity at a discount of up to 90%.</p>
</li>
<li><p>Dedicated: Most expensive option. Used for <em>security purposes</em>**,** by using a space that is not shared by anyone.</p>
</li>
</ul>
<p><strong>Uses of Instances:</strong></p>
<p><strong>On-Demand</strong>: Applications with short-term, spiky, or unpredictable workloads that cannot be interrupted. Applications being developed or tested on Amazon EC2 for the first time</p>
<p><strong>Reserved:</strong> Predictable usage or steady state, Specific capacity requirements, Pay upfront.</p>
<p><strong>Spot Instance:</strong> Applications that have flexible start and end times, that are only feasible at very low compute prices and suitable for the urgent need for large amounts of additional computing capacity.</p>
<p><strong>Dedicated hosts: Compliance requirements</strong> and regulatory requirements that may not support multi-tenant virtualization. Licensing which does not support multi-tenancy or cloud deployments.</p>
<h3 id="heading-ec2-instance-types"><strong>EC2 INSTANCE TYPES:</strong></h3>
<p>Instance type determines the hardware configuration and capabilities of the host computers when an instance or virtual machine is running. Instance types comprise varying combinations of CPU, memory, storage, and networking capacity and give you the flexibility to choose the appropriate mix of resources for your applications. Each instance type includes one or more instance sizes, allowing you to scale your resources to the requirements of your target workload.</p>
<p>Select an instance type based on the requirement of your application.</p>
<p><em>For more detail:</em> <a target="_blank" href="https://aws.amazon.com/ec2/instance-types/">https://aws.amazon.com/ec2/instance-types/</a></p>
<h2 id="heading-route-53">ROUTE 53</h2>
<p><img src="https://svr474.a2cdn1.secureserver.net/wp-content/uploads/2021/10/image-5.png" alt class="image--center mx-auto" /></p>
<p>Route 53 is Amazon’s DNS (Domain Name System) service. Allow you to map your domain names to:</p>
<ul>
<li><p>EC2 instances</p>
</li>
<li><p>Load Balancers</p>
</li>
<li><p>S3 Buckets</p>
</li>
</ul>
<h2 id="heading-elastic-load-balancers"><strong>ELASTIC LOAD BALANCERS</strong></h2>
<p><img src="https://svr474.a2cdn1.secureserver.net/wp-content/uploads/2021/10/image-3.png" alt class="image--center mx-auto" /></p>
<p>Elastic Load Balancing automatically distributes incoming application traffic across multiple servers. Capacity easily increased when needed.</p>
<p><strong>Types of Load Balancers:</strong></p>
<p><strong>Application Load Balancers:</strong></p>
<p>Operates at the OSI layer 7, and makes routing and routing decisions based on the information. Best suited for load balancing of HTTP and HTTPS traffic. They are intelligent, and you can create advanced request routing, sending specified requests to specific web servers.</p>
<p><strong>Network Load balancers:</strong></p>
<p>Best suited for load balancing of TCP traffic where extreme performance is required. Operating at the connection level (Layer 4), basically, layer 4 wants super fast performance &amp; super fast speed. Network Load Balancers are <em>capable of handling millions of requests per second</em> while maintaining ultra-low latencies. It is <em>AWS’s most expensive load balancer but is</em> used in production especially when the latency is an issue.</p>
<h4 id="heading-classic-load-balancers"><strong>CLASSIC LOAD BALANCERS:</strong></h4>
<p>They are the legacy Elastic Load Balancers. Load balancing of HTTP/HTTPS applications and use Layer 7-specific features, such as X-Forwarded and sticky sessions. You can also use strict Layer 4 load balancing for applications that rely purely on the TCP Protocol. Classic Load Balancer is intended for applications that were built within the EC2-Classic network.</p>
<p><strong>X-Forwarded-For Header:</strong> Identify the originating IPv4 address of a client connecting through a load balancer</p>
<h2 id="heading-cloud-front"><strong>CLOUD FRONT</strong></h2>
<p>Cloud front is Amazon’s <strong>CDN (Content delivery network)</strong>.</p>
<p>CDN is a system of distributed servers (network) that deliver webpages and other web content to a user based on the geographic locations of the user, the origin of the webpage, and a content delivery server. CDN is easy and cost-effective way to distribute content with low latency and high data transfer speed.</p>
<p>Explain by an example, Imagine a website running from London, and has users at geographically dispersed all around the world. So, instead of each user accessing the files directly between the users, we introduce this concept called <strong>Edge locations</strong>. An edge location is simply a collection of servers that are in geographically dispersed data centers. And these are used by CloudFront to keep a cache of copies of your object, and this means that instead of requesting content from a server in London, users can access that content from the edge location. So, once the request is made, the edge location forwards the request to the server in London, so it downloads the files and it caches them locally. This provides a much faster response time. It means that your requests are only going to that local edge location, they’re not going all the way to the main server.</p>
<p><img src="https://cloudacademy.com/wp-content/uploads/2017/07/Screen-Shot-2017-07-05-at-13.15.35.png" alt="AWS global infrastructure, region table, data center location, availability" class="image--center mx-auto" /></p>
<ul>
<li><p><strong>Edge Location:</strong> Location where content is cached and can also be written. Separate to an AWS Region/Availability Zone.</p>
</li>
<li><p><strong>Origin:</strong> This is the origin of all the files that the CDN will distribute. Origins can be an S3 Bucket, an EC2 Instance, an Elastic Load Balancer, or Route53.</p>
</li>
<li><p><strong>Distribution:</strong> This is the name given the origin and configuration settings for the content to distribute using CDN.</p>
<ul>
<li><p><strong>Web Distribution:</strong> Typically used for websites. HTTP/HTTPS</p>
</li>
<li><p><strong>RTMP (Real-Time Messaging Protocol):</strong> Used for Media Streaming.</p>
</li>
</ul>
</li>
</ul>
<p>Amazon CloudFront can be used to deliver your entire website, including dynamic, static, streaming and interactive content using a global network of edge locations. Requests for your content are automatically routed to the nearest edge location, so content is delivered with the best possible performance.</p>
<p>CloudFront is optimized to work with other Amazon Web Services, like Amazon S3, EC2, Elastic Load Balancer, and Route 53. Amazon CloudFront also works seamlessly with any non-AWS origin server, which stores the original, definitive versions of files.</p>
<p>Objects are cached for a period which is a <strong>TTL(Time to Live)</strong> i.e; 24 Hrs. Cached objects can be cleared, but you will be charged.</p>
<p><strong>S3 Transfer Acceleration:</strong> Enables fast, easy and secure transfers of files over long distances between your end users and an S3 bucket. Transfer Acceleration takes advantage of Amazon CloudFront’s globally distributed edge locations. As the data arrives at an edge location, data is routed to Amazon S3 over an optimized network path.</p>
<h2 id="heading-aws-databases"><strong>AWS: DATABASES</strong></h2>
<h3 id="heading-rds-relational-database-service"><strong>RDS (RELATIONAL DATABASE SERVICE)</strong></h3>
<p><img src="https://svr474.a2cdn1.secureserver.net/wp-content/uploads/2021/10/image.jpeg" alt class="image--center mx-auto" /></p>
<p>RDS is used for OLTP (Online Transaction Processing) workload.</p>
<p>OLTP processes data from transactions in real-time like customer orders, banking transactions, payments and booking systems.</p>
<p>Amazon RDS is available on several database instance types – optimized for memory, performance or I/O – and provides you with six familiar database engines to choose from, including Amazon Aurora, PostgreSQL, MySQL, MariaDB, Oracle Database, and SQL Server.</p>
<h4 id="heading-benefits"><strong>BENEFITS:</strong></h4>
<ul>
<li><p>Easy to set up and operate: No need for infrastructure provisioning, and no need for installing and maintaining database software.</p>
</li>
<li><p>Highly scalable: Amazon RDS engine types allow you to launch one or more Read Replica to offload read traffic from your primary database instance.</p>
</li>
<li><p>Automatically backup and allows taking manual backup of the database as a snapshot.</p>
</li>
</ul>
<h3 id="heading-features-of-rds"><strong>FEATURES OF RDS</strong></h3>
<h4 id="heading-multi-az"><strong>MULTI AZ:</strong></h4>
<p>Multi-AZ is an exact copy of the production database in another Availability Zone.</p>
<p>AWS handles the replication for you, so when your production database is written to the primary database in a particular AZ, then this write will automatically be synchronized to the standby database which is located in another AZ.</p>
<p>In the event of planned database maintenance, DB Instance failure, or an Availability Zone failure, Amazon RDS will automatically failover to the standby so that database operations can resume quickly without administrative intervention.</p>
<p>RDS type that can be configured as Multi-AZ: PostgreSQL, MySQL, MariaDB, Oracle Database, and SQL Server.</p>
<p><em>Multi-AZ is for Disaster Recovery only. It is not primarily used for improving performance. For performance improvement, you need a Read replica.</em></p>
<h4 id="heading-read-replica"><strong>READ REPLICA:</strong></h4>
<p>Read replicas is a read-only copies of your primary database. This is achieved by using Asynchronous replication from the primary RDS instance to the read replica. You use read replicas primarily for a very read-heavy database workload and take the load off the primary database.</p>
<p>Read Replica can be located in the same AZ as the primary database. It can also be in cross AZ i.e; a completely different AZ, or it can even be in cross region, located in a completely different region.</p>
<p><strong>Key Points:</strong></p>
<ul>
<li><p>Scaling Read Performance: Read replicas are used for scaling, not for disaster.</p>
</li>
<li><p>Require Automatic Backup: Must have automatic backups turned on in order to deploy a read replica.</p>
</li>
<li><p>Multiple Read Replica: MySQL, PostgreSQL, MariaDB, SQL and Oracle allow you to add up to 5 read replica copies of any database.</p>
</li>
</ul>
<p><strong>RDS Backups</strong></p>
<ol>
<li><strong>Automated Backups:</strong></li>
</ol>
<p>These are enabled by default. Allows you to recover your database to any point in time within a “retention period”. The retention period can be between 1 -35 days. Automated Backups will take a full daily snapshot and will also store transaction logs throughout the day. When you do a recovery, AWS will first choose the most recent daily backup, and then apply transaction logs relevant to that day. This allows you to do a point-in-time recovery down to a second, within the retention period.</p>
<p>Automated Backup is stored in S3 and you get free storage space equal to the size of your database.</p>
<p>2. <strong>Database Snapshots:</strong></p>
<p>DB Snapshots are done manually (i.e; user-initiated). No retention period, manual snapshots are not deleted even after you delete the original RDS instance, including any automated backup. Provide a snapshot of the storage volume attached to the DB instance.</p>
<h3 id="heading-elasticache"><strong>ELASTICACHE</strong></h3>
<p>Elasticache is an in-memory cache. This web service makes it easy to deploy, operate, and scale an <strong>in-memory cache</strong> in the cloud. The service improves the performance of web applications by allowing you to retrieve information from a fast in-memory cache, instead of relying entirely on a slower disk-based database.</p>
<p>Amazon ElastiCache can be used to significantly improve latency and throughput for many read-heavy application workloads (such as social networking, gaming, media sharing and Q&amp;A portals) or compute-intensive workloads ( such as a recommendation engine). Caching improves application performance by storing critical pieces of data in memory for low-latency access.</p>
<p><img src="https://cloudacademy.com/wp-content/uploads/2015/11/ElastiCache-300x291.png" alt="Amazon ElastiCache - An Introduction" class="image--center mx-auto" /></p>
<p><strong>Types of Elasticache:</strong></p>
<ul>
<li><p><strong>Memcached:</strong> In-memory, key-value data store, Object caching is the primary goal. Scale horizontally, but there is no persistence, Multi-AZ or failover. Keep things as simple as possible.</p>
</li>
<li><p><strong>Redis:</strong> In-memory, key-value data store. A more sophisticated solution with features like persistence, replication, Multi-AZ and failover. Support sorting and ranking data in memory such as leaderboards and also support more advanced data types, such as lists, hashes and sets. ElastiCache supports Master/Slave replication and Multi-AZ which can be used to achieve cross-AZ redundancy.</p>
</li>
</ul>
<p><em>Elasticache is the best choice if the database is read-heavy and not prone to frequent changing.</em> <em>Elasticache will not help in alleviating heavy write loads, so you may need to scale up the database.</em></p>
<h3 id="heading-dynamodb">DynamoDB</h3>
<p><img src="https://svr474.a2cdn1.secureserver.net/wp-content/uploads/2021/10/image-1.jpeg" alt class="image--center mx-auto" /></p>
<p>Amazon DynamoDB is a fast and flexible NoSQL database service for all applications that need consistent, single-digit millisecond latency at any scale. It is a fully managed database and supports both document and key-value data models, Documents can be written in JSON, HTML or XML. Its flexible data model and reliable performance make it a great fit for mobile, web, gaming, ad tech, IoT and many other applications.</p>
<ul>
<li><p>DynamoDB data stored in SSD (Solid State Desks) storage helps to give you consistently fast performance for reads and writes.</p>
</li>
<li><p>Spread Across 3 geographically distinct data centers to avoid failure.</p>
</li>
<li><p>Choice of 2 consistency models for DynamoDB read:</p>
<ul>
<li><p>Eventual Consistent Reads (Default)</p>
</li>
<li><p>Strongly Consistent Reads</p>
</li>
</ul>
</li>
</ul>
<p><strong>Eventually Consistent Reads:</strong></p>
<p>Consistency across all copies of data across the 3 locations is usually reached within a second. Repeating a read after a short time should return the updated data. (Best Read Performance)</p>
<p><strong>Strongly Consistent Reads:</strong></p>
<p>A strongly consistent read returns a result that reflects all writes that received a successful response before the read.</p>
<p><strong>DynamoDB Transactions</strong></p>
<ul>
<li><p>DynamoDB Transactions are to support mission-critical applications, which need an all-or-nothing approach to their database transactions.</p>
</li>
<li><p><strong>ACID Transactions</strong>, ACID describes the ideal properties of a database transaction.</p>
</li>
</ul>
<p>A: (Atomic) transaction is treated as a single unit.</p>
<p>C: (Consistent) means that it must be a valid transaction, it must leave the database in a valid state and that prevents any database corruption, or data integrity issues.</p>
<p>I: (Isolated) mean there is no dependency between different transactions, they are completed either in parallel or sequentially, effect going to be the same</p>
<p>D: (Durable) means that when a transaction has been committed, going to remain committed even after a system failure or a power loss, once it has been committed that means it’s going to be written to disk rather than being held in memory.</p>
<p><strong>In short, the main idea is that transaction that possesses these qualities can be treated as a single operation on the data and the durability of the operation is guaranteed in the event of a system or power failure</strong></p>
<ul>
<li><p>Read or write multiple items across multiple tables as an all-or-nothing operation</p>
</li>
<li><p>Check for a pre-requisite condition before writing to a table</p>
</li>
</ul>
<p><strong>DynamoDB is made up of:</strong></p>
<ul>
<li><p>Tables</p>
</li>
<li><p>Items (a row of data in a table)</p>
</li>
<li><p>Attributes (a column of data in a table)</p>
</li>
<li><p>Supports key-value and document data structures.</p>
</li>
<li><p>Key = The name of the data, Value = the data itself.</p>
</li>
</ul>
<p><strong>DynamoDB – Primary Keys</strong></p>
<ul>
<li><p>DynamoDB stores and retrieves data based on a Primary Key</p>
</li>
<li><p>2 Types of Primary Keys:</p>
<ul>
<li><p>Partition Key: unique attribute (e.g. user ID)</p>
<ul>
<li><p>The value of the Partition key is input to an internal hash function which determines the partition or physical location on which the data is stored.</p>
</li>
<li><p>If you are using the Partition Key as your Primary Key, then no two items can have the same Partition Key.</p>
</li>
</ul>
</li>
<li><p>Composite Key (Partition Key + Sort Key): in combination (e.g. Same user posting multiple times to a forum</p>
<ul>
<li><p>The primary key would be a Composite key consisting of a Partition Key – User ID, Sort Key- Timestamp of the post</p>
</li>
<li><p>2 items may have the same Partition Key, but they must have a different Sort Key.</p>
</li>
<li><p>All items with the same Partition Key are stored together, then sorted according to the sort key value.</p>
</li>
<li><p>Allows you to store multiple items with the same partition key.</p>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<p><img src="https://d2908q01vomqb2.cloudfront.net/887309d048beef83ad3eabf2a79a64a389ab1c9f/2018/09/10/dynamodb-partition-key-1.gif" alt="Choosing the Right DynamoDB Partition Key | AWS Database Blog" class="image--center mx-auto" /></p>
<p><strong>Access Control</strong></p>
<ul>
<li><p>Authentication and Access Control are managed using AWS IAM.</p>
</li>
<li><p>You can create an IAM user within your AWS account which has specific permissions to access and create DynamoDB tables.</p>
</li>
<li><p>You can create an IAM role that enables you to obtain temporary access keys which can be used to access DynamoDB.</p>
</li>
<li><p>You can also use a special IAM Condition to restrict user access to only their records.</p>
</li>
</ul>
<h3 id="heading-s3-simple-storage-serverhttpsfincharyacoms3-simple-storage-server"><a target="_blank" href="https://fincharya.com/s3-simple-storage-server/"><strong>S3 (SIMPLE STORAGE SERVER)</strong></a></h3>
<p><img src="https://svr474.a2cdn1.secureserver.net/wp-content/uploads/2021/10/image-6.png" alt class="image--center mx-auto" /></p>
<p>Provides secure, durable, highly scalable object storage. Amazon S3 is easy to use, with a simple web services interface to store and retrieve any amount of data from anywhere on the web. This means S3 is a place to put flat files (not changing files) i.e; pictures, videos, and text files.</p>
<p>S3 is <strong>Object-based storage only —</strong> allows you to upload files, images, documents, videos, and code. It cannot be used to run an operating system or database.</p>
<p><strong>The basics of S3 are</strong>:</p>
<ul>
<li><p>Object size can be from 0 Bytes to 5TB.</p>
</li>
<li><p>Unlimited Storage: Total volume of data and the number of objects you can store is unlimited</p>
</li>
<li><p>Files are stored in Buckets.</p>
</li>
<li><p>S3 is a <strong>universal namespace.</strong> That is, names must be unique globally. Ex: <a target="_blank" href="https://bucket-name.s3.eu-west-1.amazonaws.com/image1.jpg">https://bucket-name.s3.eu-west-1.amazonaws.com/image1.jpg</a></p>
</li>
<li><p>When you upload a file to S3, you will receive an HTTP 200 code if the upload was successful.</p>
</li>
</ul>
<p>S3 is a safe place to store files. The data is spread across multiple devices and facilities to ensure availability and durability.</p>
<h4 id="heading-characteristics"><strong>CHARACTERISTICS:</strong></h4>
<ul>
<li><p>Tiered Storage: Offers a range of storage classes designed for different use cases.</p>
</li>
<li><p>Lifecycle Management: Define a rule to automatically transition objects to a cheaper storage tier or delete objects that are no longer required after a set period.</p>
</li>
<li><p>Versioning: All versions of an object are stored and can be retrieved, including deleting objects.</p>
</li>
</ul>
<p><strong>S3 Storage Classes</strong></p>
<ol>
<li><p><strong>S3 Standard:</strong> 99.99% availability, 99.9999..% durability(11 9’s), stored redundantly across multiple devices in multiple facilities(&gt;=3 AZs), and is designed to sustain the loss of 2 facilities concurrently. Best for websites, mobile and gaming applications and big data analytics.</p>
</li>
<li><p><strong>S3 – IA (Infrequently Accessed):</strong> For data that is accessed less frequently, but requires rapid access when needed. Lower fee for per GB storage and a per GB retrieval fee. Great for long-term storage and backups.</p>
</li>
<li><p><strong>S3 One Zone – IA:</strong> For where you want a lower–cost option for infrequently accessed data, but data is stored redundantly within a single AZ.</p>
</li>
<li><p><strong>S3- Intelligent Tiering</strong>: Designed to optimize costs by automatically moving data to the most cost-effective access tier, without performance impact or operational overhead.</p>
</li>
<li><p><strong>S3 Glacier:</strong> This is a secure, durable, and low-cost storage class <strong>for data archiving</strong>. You can reliably store any amount of data at costs that are competitive with or cheaper than on-premises solutions. Retrieval times are configurable from minutes to hours.</p>
</li>
<li><p><strong>S3 Glacier Deep Archive</strong>:  S3 Glacier Deep Archive is Amazon S3’s lowest-cost storage class where a retrieval time of 12 hours is acceptable e.g., financial records that may be accessed once or twice per year.</p>
</li>
</ol>
<h3 id="heading-ebselastic-block-store-volume"><strong>EBS(ELASTIC BLOCK STORE) VOLUME</strong></h3>
<p><img src="https://svr474.a2cdn1.secureserver.net/wp-content/uploads/2021/10/image-2.png" alt class="image--center mx-auto" /></p>
<p>EBS is a highly available and scalable storage volume or disk that can be attached to EC2 instances. You can create a file system on top of these volumes, or use them in any way you would use a block device (such as a hard drive). You can dynamically change the configuration of a volume attached to an instance. With Amazon EBS, you pay only for what you use.</p>
<p><strong>Features of EBS:</strong></p>
<ul>
<li><p>Scalable: Dynamically increase capacity and change the type volume with no downtime or performance impact on your live systems.</p>
</li>
<li><p>Designed for mission-critical workloads.</p>
</li>
<li><p>Highly Available: Automatically replicated within a single availability zone to protect against hardware failures.</p>
</li>
</ul>
<p><strong>EBS Volume Types</strong></p>
<ol>
<li><strong>General Purpose SSD (gp2):</strong></li>
</ol>
<ul>
<li><p>Get a balance of price and performance</p>
</li>
<li><p>3 IOPS (IO operation per second) per GiB, up to a max of 16,000 IOPS per volume.</p>
</li>
<li><p>gp2 volumes &lt; 1TB can be burst up to 3,000 IOPS.</p>
</li>
<li><p>Great for boot vol or development and test applications which are not latency sensitive.</p>
</li>
</ul>
<ol>
<li><strong>Provisioned IOPS SSD (io1):</strong></li>
</ol>
<ul>
<li><p>High performance and the most expensive option.</p>
</li>
<li><p>Up to 64,000 IOPS per vol, 50 IOPS per GiB.</p>
</li>
<li><p>Use if you need more than 16,000 IOPS, up to 99.9% durability.</p>
</li>
<li><p>Designed for I/O intensive applications, large databases, and latency-sensitive workloads.</p>
</li>
<li><p>Suitable for OLTP (Online transaction processing)</p>
</li>
</ul>
<ol>
<li><strong>Provisioned IOPS SSD (io2):</strong></li>
</ol>
<ul>
<li><p>The latest generation of Provisioned IOPS</p>
</li>
<li><p>Higher durability and more IOPS per GiB (500 IOPS/GiB), Up to 64,000 IOPS per vol</p>
</li>
<li><p>99.999% durability</p>
</li>
</ul>
<ol>
<li><strong>Throughput Optimized HDD (st1):</strong></li>
</ol>
<ul>
<li><p>Baseline throughput of 40 MB/s per TB</p>
</li>
<li><p>Ability to burst up to 250 MB/s per TB.</p>
</li>
<li><p>Maximum throughput of 500 MB/s per vol</p>
</li>
<li><p>Used for frequently-accessed, throughput-intensive workloads.</p>
</li>
<li><p>Big Data, data warehouse, ETL(Extract Transform Load operations) and log processing.</p>
</li>
<li><p>A cost-effective way to store mountains of data.</p>
</li>
<li><p>Cannot be a boot volume.</p>
</li>
</ul>
<ol>
<li><strong>COLD HDD (sc1)</strong></li>
</ol>
<ul>
<li><p>Lowest cost option.</p>
</li>
<li><p>Baseline throughput of 12 MB/s per TB.</p>
</li>
<li><p>Ability to burst up to 80 MB/s per TB.</p>
</li>
<li><p>Max throughput of 250 MB/s per vol.</p>
</li>
<li><p>Good for data that requires fewer scans per day (Less-Frequently-accessed data).</p>
</li>
<li><p>Good for applications that need the lowest cost and performance is not a factor.</p>
</li>
<li><p>Cannot be a boot vol.</p>
</li>
</ul>
<h2 id="heading-api-gateway"><strong>API GATEWAY</strong></h2>
<p><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSfzNvGb9_Avh_Scu-U4grTcHTei6GxSfOYMw&amp;usqp=CAU" alt="Sentia Tech Blog | Amazon API Gateway types, use cases and performance" class="image--center mx-auto" /></p>
<p>API (Application Programming Interface), API is used to interact with web applications, and applications use APIs to communicate with each other. API Gateway has cashing capabilities to increase performance.</p>
<p>It is a fully managed service that makes it easy for developers to publish, maintain, monitor and secure APIs at any scale. APIs act as a “front door” for applications to access data, business logic, or functionality from your back-end services, such as applications running on EC2, code running on AWS Lambda, or any web application. This service provides a single endpoint for all client traffic interacting with the backend of your application.</p>
<p><strong>Types of API</strong></p>
<ol>
<li><p><strong>REST APIs (RE</strong>presentational <strong>S</strong>tate <strong>T</strong>ransfer): Used by 70% of the internet. It is going to use JSON (Key value pair). This api is optimized for stateless, serverless workloads.</p>
</li>
<li><p><strong>Websocket APIs</strong> are for real-time, two-way, stateful communication example chat apps.</p>
</li>
</ol>
<p><strong>Key Points:</strong></p>
<ul>
<li><p>API Gateway is serverless therefore it is low in cost and scales automatically.</p>
</li>
<li><p>Supports throttling: Throttle API Gateway to prevent your application from being overloaded by too many requests.</p>
</li>
<li><p>Logged to CloudWatch examples of API calls, latencies and errors.</p>
</li>
<li><p>Maintain multiple versions of API.</p>
</li>
</ul>
<h2 id="heading-step-function"><strong>STEP FUNCTION</strong></h2>
<p><img src="https://svr474.a2cdn1.secureserver.net/wp-content/uploads/2021/10/image-19.png" alt class="image--center mx-auto" /></p>
<p>Step Functions allows you to visualize and test your serverless applications. Step functions provide a graphical console to arrange and visualize the components of your application as a series of steps. This makes it simple to build and run multi-step applications. Step functions automatically trigger and tracks each step, and retires when there are errors, so your application executes in order and as expected. Step functions log the state of each step so that when things do go wrong, you can diagnose and debug problems quickly.</p>
<p><img src="https://d1.awsstatic.com/Getting%20Started/create-a-serverless-workflow-step-functions-lambda/03c.585ec28744d135883e456a3334b4351b01d56c97.png" alt="Create a Serverless Workflow with AWS Step Functions | AWS" /></p>
<p><strong>Key Points:</strong></p>
<ul>
<li><p>Great way to visualize your serverless application.</p>
</li>
<li><p>Step functions automatically trigger and track each step.</p>
</li>
<li><p>Step functions log the state of each step so if something goes wrong you can track what went wrong and where.</p>
</li>
</ul>
<h2 id="heading-x-ray"><strong>X-RAY</strong></h2>
<p>An X-Ray is a tool that helps developers analyze and debug distributed applications. Allowing you to troubleshoot the root cause of performance issues and errors. Provided with the service map which is a visual representation of the application</p>
<p>AWS X-Ray is a service that collects data about requests that your application serves and provides tools you can use to view, filter and gain insights into that data to identify issues and opportunities for optimization. For any traced request to your application, you can see detailed information not only about the request and response but also about calls that your application makes to downstream AWS resources, microservices, databases and HTTP web APIs.</p>
<p>The X-Ray Integrates with the following AWS services:</p>
<ul>
<li><p>Elastic Load Balancer</p>
</li>
<li><p>AWS Lambda</p>
</li>
<li><p>Amazon API Gateway</p>
</li>
<li><p>Amazon EC2</p>
</li>
<li><p>AWS Elastic Beanstalk</p>
</li>
<li><p>SNS</p>
</li>
<li><p>SQS</p>
</li>
<li><p>DynamoDB</p>
</li>
</ul>
<p>X-Ray Languages:</p>
<ul>
<li><p>Java</p>
</li>
<li><p>Go</p>
</li>
<li><p>Node.js</p>
</li>
<li><p>Python</p>
</li>
<li><p>Ruby</p>
</li>
<li><p>.Net</p>
</li>
</ul>
<p><strong>X-Ray Architecture</strong></p>
<p>X-Ray SDK automatically captures metadata for API calls made to AWS services using the AWS SDK.</p>
<p>We have an X-Ray SDK installed inside the application and this SDK sends bits of JSON to the X-Ray Daemon, and this Daemon installs on the Linux PC, and Windows PC. X-Ray Daemon takes JSON and sends it to the X-Ray API, X-Ray API stores all the data. We also have Scripts and Tools, these are normal SDKs and CLI that communicate with the X-Ray Daemon and X-Ray API directly.</p>
<p><strong>X-Ray Daemon</strong></p>
<ul>
<li><p>It is an application that listens for traffic on the port</p>
</li>
<li><p>Open source project.</p>
</li>
<li><p>Lambda and Elastic Beanstalk can use X-Ray Daemon.</p>
</li>
<li><p>Run X-Ray daemons on AWS as well as in an on-premises environment.</p>
</li>
</ul>
<p><strong>X-Ray SDK provides:</strong></p>
<ul>
<li><p>Interceptors to add to your code to trace incoming HTTP requests.</p>
</li>
<li><p>Client handlers to instrument AWS SDK clients that your application uses to call other AWS services</p>
</li>
<li><p>An HTTP client to use to instrument calls to other internal and external HTTP web services</p>
</li>
</ul>
<p><strong>Key Points:</strong></p>
<ul>
<li><p>Help you to analyze and debug applications.</p>
</li>
<li><p>Create a service map of the services used by the application.</p>
</li>
<li><p>Identify the bugs and error in your application and automatically highlights them.</p>
</li>
</ul>
<p><strong><em>Thank you for joining me this far. I hope that my notes on AWS have provided you with a valuable introduction and saved some time. I look forward to sharing more of my notes with you in the future. Until next time, happy cloud computing!"</em></strong></p>
]]></content:encoded></item><item><title><![CDATA[Introduction to Azure Virtual Machines]]></title><description><![CDATA[Azure Virtual Machines (VMs) are like your own personal computers, but they live in the cloud instead of on your desk. They're great if you need a lot of computing power and flexibility, but don't want to deal with the hassle of setting up and mainta...]]></description><link>https://siddharthqs.com/introduction-to-azure-virtual-machines</link><guid isPermaLink="true">https://siddharthqs.com/introduction-to-azure-virtual-machines</guid><category><![CDATA[Azure]]></category><category><![CDATA[virtual machine]]></category><category><![CDATA[Linux]]></category><category><![CDATA[Cloud]]></category><dc:creator><![CDATA[Siddharth]]></dc:creator><pubDate>Sat, 07 Jan 2023 21:04:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1673105814813/c2898810-1a98-4939-850a-6182b5897e48.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Azure Virtual Machines (VMs) are like your own personal computers, but they live in the cloud instead of on your desk. They're great if you need a lot of computing power and flexibility, but don't want to deal with the hassle of setting up and maintaining physical servers.</p>
<p>With Azure VMs, you can create and configure virtual machines with different operating systems, CPU and memory configurations, and other settings (highly configurable indeed). You can then use these VMs to run your applications and services. And the best part? You only pay for the VMs when you're actually using them, unlike your gym membership where you have to pay monthly, that's why I like orange theory.</p>
<p>Each VM is a fully isolated and secure environment that is configured with its own set of virtual hardware, including CPU, memory, storage, and networking resources. The size of the virtual machine is determined by the OS images and Data disk images. Azure VMs are billed at an hourly rate. A single instance VMs has an availability of 99.9% (with premium storage disks). Two instances deployed in the Availability Set will give you 99.95% availability and you can attach multiple managed disks to your Azure VMs.</p>
<h1 id="heading-create-an-azure-vm">Create an Azure VM</h1>
<p>To create an Azure Virtual Machine (VM), you will need to perform the following steps:</p>
<ol>
<li><p>Open up the Azure portal and sign in with your super secret Azure account. If you don't have an Azure account, go ahead and create one. It's like a gym membership, but for cloud computing. Yeah, you have to give your credit card info to Microsoft.</p>
</li>
<li><p>Enter "virtual machines" in the search or under services select Virtual machines.</p>
</li>
<li><p>Select "Azure virtual machine".</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1673114065908/4359dc5a-cd3a-432d-bcb6-490f5237d660.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>On the "Basics" tab, provide the following information:</p>
</li>
</ol>
<ul>
<li><p>Resource group: Choose an existing resource group or create a new one to hold the VM and other related resources.</p>
</li>
<li><p>Virtual machine name: Choose a unique name for the VM.</p>
</li>
<li><p>Region: Choose the region where you want to create the VM.</p>
</li>
<li><p>Image: Choose the image that you want to use to create the VM. You can choose from a range of pre-configured images or use a custom image.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1673114307412/38ceb34b-98a6-41f4-aa7a-8ade6de644d5.png" alt class="image--center mx-auto" /></p>
</li>
</ul>
<ol>
<li><p>On the "Size" tab, choose the size and configuration of the VM. You can choose from a range of sizes that have different combinations of CPU, memory, and storage. Don't worry, you can always change it later if you need more virtual horsepower.</p>
</li>
<li><p>On the "Settings" tab, configure any additional settings for the VM, such as networking, security, and extensions. You can also enable boot diagnostics if you want to see what your VM is thinking.</p>
</li>
<li><p>On the "Review+create" tab, review the configuration and click the "Create" button to start the deployment of your little virtual friend.</p>
</li>
</ol>
<p>When you create a VMs, it creates multiple resources such as a Virtual network, Network security group (NSG), Network Interface etc. I created a VM with the name vm1, following are the resources get created.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1673119922009/e0cc0668-123b-45ea-aab9-51c8dfbd8307.png" alt class="image--center mx-auto" /></p>
<p>Here are some web links from Microsoft to save your google search time:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://learn.microsoft.com/en-us/azure/virtual-machines/linux/quick-create-portal?tabs=ubuntu">https://learn.microsoft.com/en-us/azure/virtual-machines/linux/quick-create-portal?tabs=ubuntu</a></div>
<p> </p>
<h1 id="heading-azure-vms-sizes">Azure VMs Sizes</h1>
<p>Azure VMs come in a variety of sizes that are optimized for specific cases. They are general purposes, compute-optimized, memory-optimized and GPU etc.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://learn.microsoft.com/en-us/azure/virtual-machines/sizes">https://learn.microsoft.com/en-us/azure/virtual-machines/sizes</a></div>
<p> </p>
<p><strong><em>General purpose</em></strong> VM sizes are like the Goldilocks of computing - not too much CPU, not too little memory. They're just right for all your testing and development needs, as well as hosting small to medium databases and low to medium-traffic websites. <em>Basically, they're the Toyota VMs</em> and you will be pretty much using them every day.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://learn.microsoft.com/en-us/azure/virtual-machines/sizes-general?source=recommendations">https://learn.microsoft.com/en-us/azure/virtual-machines/sizes-general?source=recommendations</a></div>
<p> </p>
<p><strong><em>Compute-optimized</em></strong> VM sizes are like steroids for your CPU - they'll give it a massive boost, but might skimp a little on the memory. They're perfect for medium-traffic websites, network appliances that need to process a lot of data, batch processes that can take advantage of all that extra CPU power, and application servers that need to handle a lot of requests. <em>Basically, they're the muscle car of VMs</em>."</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://learn.microsoft.com/en-us/azure/virtual-machines/sizes-compute?source=recommendations">https://learn.microsoft.com/en-us/azure/virtual-machines/sizes-compute?source=recommendations</a></div>
<p> </p>
<p>The nice thing is you can check the cost of the sizes from the Azure portal. Here is the most frequently used:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1673121912721/8846ca41-8447-49fd-be21-594d0acf3a8c.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-azure-compute-unit">Azure Compute Unit</h2>
<p>Think of Azure Compute Units (ACUs) as the horsepower of your Azure Virtual Machines (VMs). ACU is currently standardized on a Small (Standard_A1) VM being 100 and all other SKUs then represent approximately how much faster that SKU can run a standard benchmark.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://learn.microsoft.com/en-us/azure/virtual-machines/acu">https://learn.microsoft.com/en-us/azure/virtual-machines/acu</a></div>
<p> </p>
<h1 id="heading-nic-network-interface">NIC (Network Interface)</h1>
<p>NIC is used to connect a virtual machine (VM) to a virtual network, and it provides the VM with a unique private IP address that is used for communication within the virtual network. Imagine that a VM is like a tiny little computer that lives inside a bigger computer (which we call a "server"). The NIC is like a little door on the VM that opens up and connects the VM to the virtual network. And the virtual network is like a big highway that all the VMs can use to talk to each other. A VM can have one or more NICs, depending on its networking configuration.</p>
<p>Now, you might be wondering, "All sounds great, but what about security? How do I make sure that only the right VMs are talking to each other?" Well, that's where Network Security Groups (NSGs) come in.</p>
<h1 id="heading-nsg-network-security-group">NSG (Network Security Group)</h1>
<p>A Network Security Group (NSG) is a virtual firewall that is used to control inbound and outbound network traffic to and from Azure resources. An NSG can be associated with a NIC to provide security for the VM that the NIC is attached to.</p>
<p>An NSG has a set of rules (protocol, port, and source or destination IP address) that specify which VMs are allowed to talk to each other, and which VMs aren't. You can think of these rules as a list of phone numbers that the NSG is allowed to call. If a VM tries to call a VM that isn't on the list, the NSG won't let the call go through.</p>
<p>To sum it up, a NIC is like a door that connects a VM to a virtual network, and an NSG is like a bouncer that controls which VMs are allowed to talk to each other.</p>
<h1 id="heading-connect-to-an-azure-virtual-machine-vm">Connect to an Azure Virtual Machine (VM)</h1>
<p>There are several ways you can connect to an Azure Virtual Machine (VM):</p>
<ol>
<li><p>Remote Desktop Protocol (RDP): You can use the Remote Desktop Connection client to connect to a VM using RDP. This is a good option if you need to interact with the VM's desktop environment. You will need to download the RDP file. Once you open the RDP file, you use the username and password during the creation of your VM in the Azure portal. RDP happens on port 3389 via TCP and UDP.</p>
</li>
<li><p>Secure Shell (SSH): You can use an SSH client to connect to a VM using the Secure Shell protocol. This is a good option if you need to run command-line tools or scripts on the VM. SSH happens at port 22 via TCP.</p>
</li>
<li><p>Azure Bastion: Azure Bastion is a service that enables you to connect to VMs using Remote Desktop Protocol (RDP) or Secure Shell (SSH) directly from the Azure portal.</p>
</li>
</ol>
<p>So far hope you get a full-mind workout just by sitting at your computer and frantically trying to remember the azure services. The good part? You dont need to worry about wearing trendy workout clothes and dealing with judgmental gym-goers.</p>
]]></content:encoded></item><item><title><![CDATA[Microsoft Azure Functions]]></title><description><![CDATA[Overview
Azure Functions is a serverless computing service that enables you to run code on-demand without having to explicitly provision or manage infrastructure. It can be used to run scripts or programs, process data, and integrate with other servi...]]></description><link>https://siddharthqs.com/microsoft-azure-functions</link><guid isPermaLink="true">https://siddharthqs.com/microsoft-azure-functions</guid><category><![CDATA[Azure]]></category><category><![CDATA[Cloud Computing]]></category><category><![CDATA[Microservices]]></category><category><![CDATA[Azure Functions]]></category><category><![CDATA[azure-devops]]></category><dc:creator><![CDATA[Siddharth]]></dc:creator><pubDate>Tue, 03 Jan 2023 07:20:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/83646466993a5d7487a1f16b44979c99.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-overview">Overview</h1>
<p><strong>Azure Functions</strong> is a serverless computing service that enables you to run code on-demand without having to explicitly provision or manage infrastructure. It can be used to run scripts or programs, process data, and integrate with other services, among other things. The nice thing is it is really easy to get up and running.</p>
<p>Here are some examples of what you can do with Azure Functions:</p>
<ul>
<li><p><strong>Run background jobs</strong> on a schedule such as backing up data, generating reports, or sending notifications. You can use the "Timer trigger" in Azure Functions to schedule the execution of a function. You can specify the schedule using a cron expression (Linux crontab format) as well.</p>
</li>
<li><p><strong>Process data</strong> as it is added to a data store. This can be useful for tasks that need to be performed every time new data is available, such as validating the data, aggregating it, or sending notifications.</p>
<ul>
<li><p>Azure Cosmos DB documents: You can use the "Cosmos DB trigger" to trigger a function when a new document is added to a collection.</p>
</li>
<li><p>Azure Storage blobs: "Blob trigger" to trigger a function when a new blob is added to a container.</p>
</li>
<li><p>Azure Queue storage messages</p>
</li>
</ul>
</li>
<li><p><strong>Automate business processes</strong>, for example, you could use an HTTP trigger to start a function when a webhook is called.</p>
</li>
<li><p><strong>Build microservices</strong> and simple APIs</p>
</li>
<li><p><strong>Build event-driven application</strong>s</p>
<ul>
<li><p>Respond to Azure Event Grid events by using subscriptions and filters</p>
</li>
<li><p>Respond to high volumes of Azure events hubs events</p>
</li>
<li><p>Responds to Azure Service bus queue and topic messages</p>
</li>
</ul>
</li>
</ul>
<p>Azure Functions can be triggered by a variety of events, including HTTP requests, changes to data in a database, or the arrival of a message on a message queue. It can also be called directly using its HTTP endpoint or a client library. Azure Functions supports a variety of programming languages, including C#, F#, Node.js, Java, PHP, JavaScript and Python.</p>
<p>Azure functions include multiple templates you can use in key scenarios. You can use the Azure portal, the Azure Functions CLI, or the Azure Functions REST API to create and manage functions.</p>
<h1 id="heading-triggers">Triggers</h1>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672713723767/0f925e0b-0879-45c4-a76b-8a2d5f810cda.png" alt class="image--center mx-auto" /></p>
<p>Here are some triggers that you can use with Azure Functions to schedule a job:</p>
<p><strong>HTTPTrigger</strong> - Functions support HTTP requests like we can do get and post requests. You can customize the trigger to respond to webhooks. Webhooks themselves come in several versions to handle different providers like GitHub and Slack.</p>
<p><strong>TimerTrigger</strong> - As the name suggests, this particular feature lets you run events on a schedule. This is provided automatically in all development environments, without the need for installing the package manually or registering the extension.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-timer?tabs=in-process&amp;pivots=programming-language-python">https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-timer?tabs=in-process&amp;pivots=programming-language-python</a></div>
<p> </p>
<p><strong>GitHub Webhook</strong> - Installing Webhooks can help you build or set up GitHub Apps. This would help in the integrations that subscribe to certain events on GitHub. Other functions include: updating an external issue tracker, updating a backup mirror, triggering CI builds and deploying to your production server.</p>
<p><strong>Generic Webhook</strong> - This is almost like a messaging format through which you can chat with the application of your choice. The template listens for messages and posts updates specific to the JSON payload.</p>
<p><strong>CosmosDBTrigger</strong> - Functions support trigger, input binding and output bindings for Azure Cosmos DB. Once CosmosDBTrigger listens for updates and updates across various partitions, the change feed would publish inserts and updates, but not deletions.</p>
<p><strong>BlobTrigger</strong> - With the help of this template, you can trigger a function when a blob is created/updated. WebJobs SDK monitors the log files constantly to check for new or changed blobs.</p>
<p><strong>QueueTrigger</strong> - QueueTrigger helps to trigger a function when a new update comes up on the queue. The queue message is the input to the function, and might even resend the message for a retry loop.</p>
<p><strong>EventHubTrigger</strong> - SendEvents() emits messages to the event hub. Trigger() will listen to the event and emit a new one with an incremented counter. Functions provide support for trigger and output bindings for Event Hubs.</p>
<p><strong>ServiceBusQueueTrigger</strong> - Through the service bus queue trigger, the developer can execute the code in the function every time the service bus received a message.</p>
<p><strong>ServiceBusTopicTrigger</strong> - When the function is triggered with a service bus topic message, the developer can publish and push messages to the topic.</p>
<h1 id="heading-bindings">Bindings</h1>
<p>A binding is a way to connect the input and output of your function to other services, such as storage queues, event hubs, and service bus queues. When you create a function, you can use bindings to access data from these external services without writing any additional code. Instead, you can use declarative bindings to specify the input and output of your function in the function's configuration.</p>
<p><img src="https://azurecomcdn.azureedge.net/cvt-6ce4fb2122db3c5c8ff787c6c9f4d1291ae55347930af2c428fc09f6a6dc5b03/images/page/products/functions/value-prop-3.gif?638083180604977451" alt class="image--center mx-auto" /></p>
<p>There are different types of bindings available in Azure Functions, including:</p>
<ul>
<li><p><strong>Input bindings</strong>: These bindings allow your function to receive data from an external service. For example, you can use an input binding to read data from a storage queue or an event hub.</p>
</li>
<li><p><strong>Output bindings</strong>: These bindings allow your function to write data to an external service. For example, you can use an output binding to write data to a storage table or a service bus queue.</p>
</li>
<li><p><strong>Trigger bindings</strong>: These bindings define the event that will cause your function to be executed. For example, you can use a trigger binding to specify that your function should be executed when a new item is added to a storage queue, or when a new message is received on an event hub.</p>
</li>
</ul>
<p>You can use bindings to simplify the code in your functions and make it easier to connect to external services. You can also use bindings to enable your functions to scale automatically in response to changes in the workload.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-triggers-bindings?tabs=csharp">https://learn.microsoft.com/en-us/azure/azure-functions/functions-triggers-bindings?tabs=csharp</a></div>
<p> </p>
<h1 id="heading-steps-to-create-azure-functions">Steps to create Azure functions</h1>
<ol>
<li><p>Sign in to the Azure portal.</p>
</li>
<li><p>Click the "<strong>Create a resource</strong>" button in the top left corner of the portal.</p>
</li>
<li><p>In the "Search the Marketplace" field, enter "Function App" and press Enter.</p>
</li>
<li><p>Click the "Function App" item in the search results.</p>
</li>
<li><p>In the "<strong>Create Function App</strong>" blade, enter a name for your function app in the "Name" field.</p>
</li>
<li><p>Choose the subscription and resource group you want to use for your function app.</p>
</li>
<li><p>Choose a hosting plan and location for your function app.</p>
</li>
<li><p>Click the "Create" (Review + create) button to create your function app.</p>
</li>
<li><p><strong>Go to resources</strong> to view your new function app.</p>
</li>
</ol>
<p>Once your function app has been created, you can create a new function by following these steps:</p>
<ol>
<li><p>In the Azure portal, navigate to your function app.</p>
</li>
<li><p>Click the "Functions" tab in the function app blade.</p>
</li>
<li><p>Click the "Add" button in the top left corner of the blade.</p>
</li>
<li><p>Choose a trigger for your function. A trigger is an event that causes your function to be executed.</p>
</li>
<li><p>Choose a language for your function.</p>
</li>
<li><p>Enter a name for your function.</p>
</li>
<li><p>Click the "Create" button to create your function.</p>
</li>
<li><p>Write your code for the function in the Azure portal, or use a local development environment to develop your function and then deploy it to Azure.</p>
</li>
<li><p>Test your function by triggering it and verifying that it works as expected.</p>
</li>
<li><p>Publish your function by clicking the "Save and run" button in the Azure portal.</p>
</li>
</ol>
<h1 id="heading-azure-function-folder-structure">Azure function folder structure</h1>
<p>The code for all the functions in a specific function app is located in a root project folder, myFunctionApp in our case using python.</p>
<pre><code class="lang-plaintext">myFunctionApp/
|-- host.json
|-- local.settings.json
|-- requirements.txt
|-- my_function/
    |-- __init__.py
    |-- function.json
    |-- main.py
</code></pre>
<p>Here is a brief explanation of each file and folder:</p>
<ul>
<li><p><code>host.json</code>: This file contains global configuration settings for the Azure Functions runtime. You can use this file to specify things like the version of the runtime, the number of workers to use, and the size of the function's memory allocation.</p>
</li>
<li><p><code>local.settings.json</code>: This file contains local configuration settings for your function app, such as the values of connection strings and app settings. This file is used during local development and is not deployed to Azure.</p>
</li>
<li><p><code>requirements.txt</code>: This file lists the Python packages that your function app depends on. The Azure Functions runtime will install these packages when you deploy your function app to Azure.</p>
</li>
<li><p><code>my_function/</code>: This folder contains the code and configuration for a specific function within your function app. The name of the folder should match the name of the function.</p>
</li>
<li><p><code>__init__.py</code>: This file is optional, but it can be used to define the namespace for your function.</p>
</li>
<li><p><code>function.json</code>: This file contains the configuration for your function, including the bindings, triggers, and other settings.</p>
</li>
<li><p><a target="_blank" href="http://main.py"><code>main.py</code></a>: This file contains the code for your function.</p>
</li>
</ul>
<h1 id="heading-azure-function-example-using-python">Azure Function example using Python</h1>
<p>To use the azure function service, you will need to install a Visual Studio code and the "Azure Functions" extension.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> azure.functions <span class="hljs-keyword">as</span> func
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>(<span class="hljs-params">req: func.HttpRequest</span>) -&gt; func.HttpResponse:</span>
    name = req.params.get(<span class="hljs-string">'name'</span>)
    <span class="hljs-keyword">if</span> name:
        <span class="hljs-keyword">return</span> func.HttpResponse(<span class="hljs-string">f"Hello <span class="hljs-subst">{name}</span>!"</span>)
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> func.HttpResponse(
             <span class="hljs-string">"Please pass a name in the request body"</span>,
             status_code=<span class="hljs-number">400</span>
        )
</code></pre>
<h1 id="heading-best-practices-using-functions">Best practices using functions</h1>
<ol>
<li><p>Functions should be stateless and idempotent.</p>
</li>
<li><p>Use queues for cross-function communication. If you require direct communication, consider durable functions or Azure Logic Apps.</p>
</li>
<li><p>Avoid long-running functions.</p>
</li>
</ol>
<h1 id="heading-durable-functions">Durable Functions</h1>
<p>Azure Durable Functions is an extension of Azure Functions that lets you write stateful functions in a serverless environment. It allows you to define workflows that span multiple functions and can be long-running</p>
<p>Durable Functions use the concept of "orchestrators" and "activities" to define and execute workflows. An orchestrator is a special type of function that coordinates the execution of one or more activity functions. Activity functions are ordinary Azure Functions that perform specific tasks as part of the workflow.</p>
<p>Durable Functions provides built-in support for state management, checkpoints, and restarting failed workflows, so you can focus on writing the business logic of your functions without worrying about the underlying infrastructure.</p>
<h2 id="heading-common-use-cases">Common use cases:</h2>
<ol>
<li><p>Function chaining: Using the output of one function as an input to another.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674326490562/b9668b6f-348a-4b6f-9c8a-ee58c8f391e5.png" alt class="image--center mx-auto" /></p>
</li>
<li><p>Fan out /fan in: Functions are executed in parallel, and their aggregation is used in a single function.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674326541709/6cc9cd02-4269-4642-b460-300a244844ae.png" alt class="image--center mx-auto" /></p>
</li>
</ol>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-create-portal">https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-create-portal</a></div>
]]></content:encoded></item><item><title><![CDATA[Monte Carlo Simulation using Rust Part-1]]></title><description><![CDATA[In a nutshell, the concept of Monte Carlo simulation is pretty straightforward; it involves generating random numbers and averaging of the outcome. We can use this technique for evaluating probability problems to complex integral equations. The two p...]]></description><link>https://siddharthqs.com/monte-carlo-simulation-using-rust-part-1</link><guid isPermaLink="true">https://siddharthqs.com/monte-carlo-simulation-using-rust-part-1</guid><category><![CDATA[monte carlo]]></category><category><![CDATA[simulation]]></category><category><![CDATA[numerical analysis]]></category><category><![CDATA[integration]]></category><category><![CDATA[Rust]]></category><dc:creator><![CDATA[Siddharth]]></dc:creator><pubDate>Tue, 15 Nov 2022 16:12:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/lhnOvu72BM8/upload/v1667446181537/Y3Wl-RSHH.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In a nutshell, the concept of Monte Carlo simulation is pretty straightforward; it involves generating random numbers and averaging of the outcome. We can use this technique for evaluating probability problems to complex integral equations. The two popular examples are estimating the value of π(pi) and integrating x square using Monte Carlo. Let's start with an example, and then we'll go over the concepts in greater depth.</p>
<h1 id="heading-examples-of-monte-carlo-simulation">Examples of Monte Carlo Simulation</h1>
<h2 id="heading-1-estimation-of-pi">1. Estimation of Pi</h2>
<p>Let's consider a circle of unit radius centered at (0,0) enclosed in a square. </p>
<pre><code class="lang-rust"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">Point</span></span> {
        x: <span class="hljs-built_in">f64</span>,
        y: <span class="hljs-built_in">f64</span>,
    }
</code></pre>
<p>The ratio of the area of the circle and square is:
$$ \pi r^2 / 4r^2 = \pi/4$$
We count both the overall number of points and the number of points that are located inside the circle. We can determine if a point is contained inside the circle by calculating its distance from the origin.</p>
<pre><code class="lang-rust"><span class="hljs-keyword">impl</span> Point {
        <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">in_circles</span></span>(&amp;<span class="hljs-keyword">self</span>) -&gt; <span class="hljs-built_in">bool</span> {
            <span class="hljs-keyword">let</span> distance = (<span class="hljs-keyword">self</span>.x.powi(<span class="hljs-number">2</span>)   + <span class="hljs-keyword">self</span>.y.powi(<span class="hljs-number">2</span>)).sqrt();
            <span class="hljs-keyword">if</span> distance&lt;=<span class="hljs-number">1.0</span>{
                <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
            }
            <span class="hljs-keyword">else</span>{
                <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
            }
        }
    }
</code></pre>
<p>If we divide the number of points inside the circle by the total number of points, we get the probability of a point falling inside a circle, which should be equal to π / 4.
Let's have a look at the code for counting the number of points within the circle:</p>
<pre><code class="lang-rust">    <span class="hljs-keyword">let</span> number_of_simulation = <span class="hljs-number">100000</span>;
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> in_circle_count = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..number_of_simulation{
        <span class="hljs-keyword">let</span> x:<span class="hljs-built_in">f64</span> = Uniform::new(-<span class="hljs-number">1.0</span>,<span class="hljs-number">1.0</span>).sample(&amp;<span class="hljs-keyword">mut</span> rng);
        <span class="hljs-keyword">let</span> y:<span class="hljs-built_in">f64</span> = Uniform::new(-<span class="hljs-number">1.0</span>,<span class="hljs-number">1.0</span>).sample(&amp;<span class="hljs-keyword">mut</span> rng);
        point.x = x;
        point.y = y;
        <span class="hljs-keyword">if</span> point.in_circles(){
            in_circle_count+=<span class="hljs-number">1</span>;
        }
    }
</code></pre>
<p>Once we get the total number of points that fall in the circle, we can estimate the value of pi as follows:
$$  In \space circle \space points / total \space points =  \pi/4 $$
$$
\pi = 4* In \space circle \space points / total \space points
 $$</p>
<pre><code class="lang-rust">    <span class="hljs-keyword">let</span> pi = (in_circle_count <span class="hljs-keyword">as</span> <span class="hljs-built_in">f64</span>) / (number_of_simulation <span class="hljs-keyword">as</span> <span class="hljs-built_in">f64</span>)*<span class="hljs-number">4.0</span>;
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>,pi);
<span class="hljs-number">3.140851</span>
</code></pre>
<h2 id="heading-2-integrate-x-square">2. Integrate x square</h2>
<p>Another example is integrating x^2. 
$$ I = \int_0^1 x^2 dx  = [x^3/3]^1_0 = 1/3$$
It might be surprising to a few people, but if you just simulate a few uniformly distributed points between 0 and 1, and take the average of the function that is x^2 in our case, you can get the approximation of this integral.  </p>
<pre><code class="lang-rust">    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> rng = rand::thread_rng();
    <span class="hljs-keyword">let</span> number_of_simulation = <span class="hljs-number">100000</span>;
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> sum_of_simulation =<span class="hljs-number">0.0</span>;
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-number">0</span>..number_of_simulation{
        <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> x:<span class="hljs-built_in">f64</span> = Uniform::new(<span class="hljs-number">0.0</span>,<span class="hljs-number">1.0</span>).sample(&amp;<span class="hljs-keyword">mut</span> rng);
        sum_of_simulation+=x.powi(<span class="hljs-number">2</span>);
    }
    <span class="hljs-keyword">let</span> avg = sum_of_simulation / (number_of_simulation <span class="hljs-keyword">as</span> <span class="hljs-built_in">f64</span>);
    <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{}"</span>,avg);
<span class="hljs-number">0.3324825398482972</span>
</code></pre>
<p>I am sure by now this technique to solve integrals sound powerful and simple enough. However, it is computationally expensive so Rust is the natural choice for this. Let's look at the concepts to see how it actually happens.</p>
<h1 id="heading-theory-and-concepts">Theory and Concepts</h1>
<p>Let X be a stochastic variable with expected <code>µ = E[X]</code> and variance <code>σ^2 = Var(X)</code>. Assume that we want to calculate <code>µ = E[X]</code> but there is no closed formula for <code>E[X]</code>. An excellent way to find this is through Monte Carlo simulations. Thanks to the law of large numbers, Monte Carlo simulation may provide an approximation of <code>E[X]</code>. </p>
<p>Let us illustrate an example of Monte Carlo simulation: </p>
<ul>
<li>First, simulate n independent and equally distributed stochastic variables <code>X1, X2, X3, .... Xn</code>, with all having the same distribution as X, with the expected value  <code>µ = E[X]</code> and variance <code>Var(X)</code></li>
<li>Now calculate the average, an approximation of the expected value µ: $$ \widetilde{\mu} = \frac{1}{n} \sum_{i=1}^{n} X_i $$
This suggests that with enough simulations n, our approximated value will be close or you can say the average converges to our expected value. This means the convergence of random variables is necessary for our simulation to work. 
Let's review basic probability theory concepts to understand it:</li>
</ul>
<h2 id="heading-convergence-of-random-variables">Convergence of Random Variables</h2>
<p>We need to define convergence because it could mean different things and proof of the law of large numbers depends on this.
Let (Ω, F, P) be a probability space and let {Xn} n∈N be a sequence of real-valued random variables defined on this probability space. We have the following convergence definition:</p>
<h3 id="heading-1-point-wise-convergence-or-sure-convergence">1. Point-wise convergence or sure convergence</h3>
<p> Let Xn be a real-valued sequence, we say it converges point-wise or surely to X if
$$ X_n(\omega) \rightarrow X, \space  \forall \omega \in \Omega $$ 
This notion of convergence is exactly analogous to that defined for regular functions. Since this notion is too strict for most practical purposes, and neither does it consider the measurability of the random variables nor the probability measure P(·), we use other definitions to prove the limiting theorem</p>
<h3 id="heading-2-almost-sure-convergence-or-convergence-with-probability-1">2. Almost sure convergence or convergence with probability 1</h3>
<p>A sequence of random variables {Xn}n∈N is said to converge almost surely or with probability 1 (denoted by a.s. or w.p. 1) to X if
$$ P(\omega \mid (X_n(\omega) \rightarrow X)) = 1, \space  \forall \omega \in \Omega $$ 
Almost sure convergence demands that the set of ω’s where the random variables converge have a probability one.</p>
<h3 id="heading-3-convergence-in-probability">3. Convergence in probability</h3>
<p>A sequence of random variables {Xn}n∈N is said to converge in probability (denoted by i.p.) to X if
$$ \lim_{n\to\infty} P( \mid X_n - X \mid &gt; \epsilon ) = 0, \space  \forall \epsilon &gt; 0 $$ </p>
<h3 id="heading-4-convergence-in-rth-mean">4. Convergence in rth mean</h3>
<p>A sequence of random variables {Xn}n∈N is said to converge in rth mean to X if
$$ \lim_{n\to\infty} E( \mid X_n - X \mid ^r ) = 0$$
r = 2 is most often used and called mean-squared.</p>
<h3 id="heading-5-convergence-in-the-distribution-or-weak-convergence">5. Convergence in the distribution or weak convergence</h3>
<p>A sequence of random variables {Xn}n∈N is said to converge in distribution to X if
$$ \lim_{n\to\infty} F_Xn(x) = F_X(x), \forall x \in R $$
here Fx() is continuous. </p>
<h2 id="heading-law-of-large-numbers">Law of Large Numbers</h2>
<p>This could be considered the backbone of the Monte Carlo simulation. It provides the mean of the average value of random variables. This is the theorem that says that the sample average of a large number of i.i.d. random variables converges to the expected value. Depending on the definition of convergence, we have weak law and strong law of large numbers.</p>
<h3 id="heading-weak-law-of-large-numbers">Weak Law of Large Numbers</h3>
<p>In the weak law of large numbers, we consider that the average converges to the expected value in probability (see above convergence in probability). 
Let X1, X2, . . . be i.i.d random variables with finite mean, E[X], then let
$$ Sn =  \sum_{i=1}^{n} X_i $$
$$ \frac{Sn}{n} \xrightarrow{i.p.} E[X]$$
We could prove using Chebyshev’s Inequality.</p>
<h3 id="heading-strong-law-of-large-numbers">Strong Law of Large Numbers</h3>
<p>This gives us the condition when the sample average converges almost surely to the expected value (see Almost sure convergence or convergence with probability 1). 
$$ \frac{Sn}{n} \xrightarrow{a.s.} E[X]$$
$$ P(\omega \mid ( \frac{Sn(\omega)}{n} \rightarrow E[X]) = 1$$</p>
<h2 id="heading-central-limit-theorem">Central Limit Theorem</h2>
<p>Let {Xi} be a sequence of i.i.d. random variables having finite variance. From the law of large numbers, we know that for large n, the sum Sn is approximately as big as nE[X], i.e.,
$$ \frac{Sn}{n} \xrightarrow{i.p.} E[X]$$
$$ \frac{Sn-nE[X]}{n} \xrightarrow{i.p.} 0$$
Thus whenever the variance of Xi is finite, the difference Sn − nE[X] grows slower as compared to n. The Central Limit Theorem (CLT) says that this difference scales as √n and the distribution approaches a normal distribution as n tends to infinity irrespective of the distribution of Xi.
 $$ \frac{Sn-nE[X]}{\sqrt{n}} \sim N(0, \sigma^2)$$
This is the reason people say that Monte Carlo "converges very slowly" or "converges with √n. If you need a tenfold improvement in accuracy, you'll need a hundredfold increase in the number of paths.</p>
<h2 id="heading-monte-carlo-integration">Monte Carlo Integration</h2>
<p>We can write integral as the expectation of a function and vice versa. </p>
<h3 id="heading-expectation">Expectation</h3>
<p>We consider X is a random variable that follows pdf fx(x). The domain of X is [a,b]
The expectation for a function is defined as:
$$ 
E[gX] = \int_a^b gx *fx dx
$$</p>
<h3 id="heading-integration">Integration</h3>
<p>Needless to say, we can use simulation to calculate the expectation.
Return to our previous example of x square integration. We can consider X follows a uniform distribution U[0,1], its pdf, fx = 1 and gx = x^2 
We can write the integral as
$$
\int_0^1 x^2 dx = \int_0^1 x^2 * fx dx = E[x^2]
$$
We assume X follows the uniform distribution. We can easily estimate the expectation of x square by taking the mean. </p>
]]></content:encoded></item></channel></rss>