<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by leangaurav on Medium]]></title>
        <description><![CDATA[Stories by leangaurav on Medium]]></description>
        <link>https://medium.com/@leangaurav?source=rss-8ed82d391e34------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CvPJLHyfOtQ9PvyEeaQDGQ.jpeg</url>
            <title>Stories by leangaurav on Medium</title>
            <link>https://medium.com/@leangaurav?source=rss-8ed82d391e34------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:39:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@leangaurav/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Wake Up with a Clear Head (Every Single Day)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://leangaurav.medium.com/how-to-wake-up-with-a-clear-head-every-single-day-b3fcfa729b16?source=rss-8ed82d391e34------2"><img src="https://cdn-images-1.medium.com/max/2600/1*4l-v-1t8r9HCv1WXxgzeLQ.png" width="2654"></a></p><p class="medium-feed-snippet">Sometimes I would wake up early morning, very easily in a peaceful mental state with no effort at all and sometimes it would feel so hard&#x2026;</p><p class="medium-feed-link"><a href="https://leangaurav.medium.com/how-to-wake-up-with-a-clear-head-every-single-day-b3fcfa729b16?source=rss-8ed82d391e34------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://leangaurav.medium.com/how-to-wake-up-with-a-clear-head-every-single-day-b3fcfa729b16?source=rss-8ed82d391e34------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3fcfa729b16</guid>
            <category><![CDATA[sleep]]></category>
            <category><![CDATA[morning-routines]]></category>
            <category><![CDATA[lifestyle]]></category>
            <category><![CDATA[health]]></category>
            <dc:creator><![CDATA[leangaurav]]></dc:creator>
            <pubDate>Sun, 08 Nov 2026 05:14:12 GMT</pubDate>
            <atom:updated>2026-11-08T05:14:49.641Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to Use Alipay in India to Pay on Chinese Websites (I used for Deepseek)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://leangaurav.medium.com/how-to-use-alipay-in-india-to-pay-on-chinese-websites-without-shady-apks-20d5c24a3ccc?source=rss-8ed82d391e34------2"><img src="https://cdn-images-1.medium.com/max/1422/1*_a_Spn6dzZVmzNO2BNWyAQ.png" width="1422"></a></p><p class="medium-feed-snippet">I wanted to use OpenCode with Deepseek models for my software projects. So I signed up on Deepseek which requries you to top-up the wallet&#x2026;</p><p class="medium-feed-link"><a href="https://leangaurav.medium.com/how-to-use-alipay-in-india-to-pay-on-chinese-websites-without-shady-apks-20d5c24a3ccc?source=rss-8ed82d391e34------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://leangaurav.medium.com/how-to-use-alipay-in-india-to-pay-on-chinese-websites-without-shady-apks-20d5c24a3ccc?source=rss-8ed82d391e34------2</link>
            <guid isPermaLink="false">https://medium.com/p/20d5c24a3ccc</guid>
            <category><![CDATA[payments]]></category>
            <category><![CDATA[china]]></category>
            <category><![CDATA[alipay]]></category>
            <category><![CDATA[india]]></category>
            <category><![CDATA[tech-guide]]></category>
            <dc:creator><![CDATA[leangaurav]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 19:01:37 GMT</pubDate>
            <atom:updated>2026-10-23T18:22:46.769Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How I got my Oracle Cloud Free tier account back with MFA reset]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://leangaurav.medium.com/how-i-got-my-oracle-cloud-free-tier-account-back-with-mfa-reset-920a5dd0cc9c?source=rss-8ed82d391e34------2"><img src="https://cdn-images-1.medium.com/max/1468/1*Ei3KCuWg2etCOz9Of9qfag.png" width="1468"></a></p><p class="medium-feed-snippet">For a long time I couldn&#x2019;t login to my Free OCI account as my phone setup with MFA got reset. Finally found a way to connect to OCI&#x2026;</p><p class="medium-feed-link"><a href="https://leangaurav.medium.com/how-i-got-my-oracle-cloud-free-tier-account-back-with-mfa-reset-920a5dd0cc9c?source=rss-8ed82d391e34------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://leangaurav.medium.com/how-i-got-my-oracle-cloud-free-tier-account-back-with-mfa-reset-920a5dd0cc9c?source=rss-8ed82d391e34------2</link>
            <guid isPermaLink="false">https://medium.com/p/920a5dd0cc9c</guid>
            <category><![CDATA[mfa]]></category>
            <category><![CDATA[oracle-cloud]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[login]]></category>
            <category><![CDATA[oci]]></category>
            <dc:creator><![CDATA[leangaurav]]></dc:creator>
            <pubDate>Fri, 26 Dec 2025 16:31:08 GMT</pubDate>
            <atom:updated>2025-12-26T16:33:02.512Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to add swap space to Ubuntu Linux Server to prevent it from Freezing]]></title>
            <link>https://leangaurav.medium.com/how-to-add-swap-space-to-ubuntu-linux-server-to-prevent-it-from-freezing-7de2771228ee?source=rss-8ed82d391e34------2</link>
            <guid isPermaLink="false">https://medium.com/p/7de2771228ee</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[cloud-services]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[leangaurav]]></dc:creator>
            <pubDate>Sun, 24 Mar 2024 06:04:16 GMT</pubDate>
            <atom:updated>2024-06-22T07:14:28.094Z</atom:updated>
            <content:encoded><![CDATA[<h3>Save your frozen Linux Server: How to add swap space to Ubuntu</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*u3y7qfBrQ54UUA707-c-cA.png" /></figure><p>If you don’t want to read the complete thing and just get this done quick. Then just copy paste the below lines... but before that replace 1G in second command with however much space you like (probably consider hitting 👏 if it helped you)</p><pre>sudo swapon --show                  <br>sudo fallocate -l 1G /swapfile      # allocate 1G of swap space<br>sudo chmod 600 /swapfile<br>sudo mkswap /swapfile<br>sudo swapon /swapfile<br>sudo swapon --show<br>sudo echo &#39;/swapfile swap swap defaults 0 0&#39; | sudo tee -a /etc/fstab</pre><p><strong>When do I add Swap Space ?</strong></p><p>Whenever I’m working on a hobby project and I want to setup a new Linux server with Ubuntu OS, I do this as the first step. <br>I mostly use small instances/VMs in free tier 😝 from AWS or OCI or some other cloud vendor. These VMs have <strong>limited amount of RAM </strong>and <strong>often freeze </strong>due to out of memory issues when I run automated github actions or something which <strong>puts pressure on memory </strong>all of a sudden.</p><p>Adding swap right after creating server has helped me avoid frozen instances and sometimes even deleting the instance and setting up a new from sacratch again because the server froze and couldn’t come up even on reboot.</p><h4><strong>Step-1: Check some stuff</strong></h4><p><strong>Check if swap is enabled<br></strong> Below output is after I have already added swap. If there’s no swap, output will be empty.</p><pre>sudo swapon --show                  # show current swap details<br><br>NAME      TYPE SIZE  USED PRIO<br>/swapfile file   2G 25.5M   -2</pre><p><strong>Check available Memory<br></strong>️❗Take a note of available memory (RAM) from here. <br>Shows 949Mi (~1G) for me (Ignore the <em>Swap </em>bit).</p><pre>free -h<br>               total        used        free      shared  buff/cache   available<br>Mem:           949Mi       263Mi        95Mi       0.0Ki       590Mi       518Mi<br>Swap:          2.0Gi        25Mi       2.0Gi</pre><p><strong>Check available disk space<br></strong>Just see how much free space you have on disk to use for swap. Looks like I have enough 🆓disk space</p><pre>df -h<br><br>Filesystem      Size  Used Avail Use% Mounted on<br>/dev/root        20G  6.7G   13G  35% /<br>tmpfs           475M     0  475M   0% /dev/shm<br>tmpfs           190M  972K  189M   1% /run<br>tmpfs           5.0M     0  5.0M   0% /run/lock<br>/dev/xvda15     105M  6.1M   99M   6% /boot/efi<br>tmpfs            95M  4.0K   95M   1% /run/user/1000</pre><h3><strong>Step-2: Allocate Swap File</strong></h3><p>Usually I keep allocate swap space which is 1–2x the memory available on system. But it could be higher also. <br>Since I have ~1G RAM, I’m allocating swapfile of size 1G. Change to whatever you like</p><pre>sudo fallocate -l 1G /swapfile      # allocate 1G of swap space</pre><h3>Step-3: Secure swapfile by changing</h3><pre>sudo chmod 600 /swapfile</pre><h3>Step-4: Convert swap file to swap area</h3><pre>sudo mkswap /swapfile</pre><h3>Step-5: Enable swap</h3><pre>sudo swapon /swapfile</pre><h3>Step-6: Make sure swap stays even after reboot</h3><p>To make changes we did till now permanent, either<br>paste this /swapfile swap swap defaults 0 0 at end of this file /etc/fstab</p><p>OR, just run this 🙌🏻</p><pre>sudo echo &#39;/swapfile swap swap defaults 0 0&#39; | sudo tee -a /etc/fstab</pre><p>Thats it done 🙌</p><p>Now if you wish to check stuff you can run either this free -h or this swapon --show command.</p><p><strong>Note-1: If you ever wish to disable swap, you need to do this</strong></p><ol><li>Turn off swap sudo swapoff -v /swapfile</li><li>Open the file /etc/fstab and delete this entry /swapfile swap swap defaults 0 0</li><li>Delete the swap file sudo rm /swapfile</li></ol><p>I also keep all above steps handy in my <a href="https://github.com/leangaurav/docs/blob/main/guides/add_swap_space.md"><strong><em>guides</em></strong></a><strong><em> </em></strong>repo on github.</p><p><strong>Note-2: There are two ways of adding swap space</strong></p><ol><li>Swap file</li><li>Swap partition</li></ol><p>We have used Swap file here. I’ve never used the other one since this option was just enough for me always. If you wish, feel free to explore the other one.</p><p>Hope this helped😀… consider hitting 👏. Saved your precious time !! Appreciate my efforts <a href="https://www.buymeacoffee.com/leangaurav"><strong>buy me a tea</strong></a><strong> </strong>☕. You can also find me on <a href="https://in.linkedin.com/in/leangaurav"><strong>Linkedin</strong></a> and say<strong> 👋.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7de2771228ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[General keyboard(and mouse) productivity]]></title>
            <link>https://leangaurav.medium.com/general-keyboard-and-mouse-productivity-bf6578d3f303?source=rss-8ed82d391e34------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf6578d3f303</guid>
            <category><![CDATA[keyboard]]></category>
            <category><![CDATA[shortcuts]]></category>
            <category><![CDATA[keyboard-shortcuts]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[leangaurav]]></dc:creator>
            <pubDate>Tue, 24 Oct 2023 18:27:23 GMT</pubDate>
            <atom:updated>2023-10-24T18:27:23.191Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m writing this just becuase I have seen people clicking and dragging mouse just to select a single word many times. And I just wanted to write some things down immediately (Feel free to suggest more and we’ll probably add it here)🤣.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*_2F3TM8lpT8ph1-Y" /><figcaption><a href="https://unsplash.com/photos/white-orange-green-and-purple-computer-keyboard-kt-wA0GDFq8">https://unsplash.com/photos/white-orange-green-and-purple-computer-keyboard-kt-wA0GDFq8</a></figcaption></figure><p>Since I’m an engineer (software by profession), apart from general OS shortcut keys, all/most of the things will look centred around text/code editors like Sublime, VsCode, IntelliJ IDEs etc. Most of the shortcuts mentioned here are the ones which I noticed missing while pair programming with someone sharing their screen 🧑‍💻.</p><p>That urge to tell someone, please use <strong>Alt + Tab</strong> to switch to previous widow 🤣.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*tz6-ffyfcBQwIO7xysTe1A.gif" /></figure><p>Also I’ll try to write windows and mac shortcuts separately (gradually over ⌛), but mostly switching <strong>Ctrl</strong> with <strong>CMD</strong> should do the job.</p><p>Lets get started 🙆🏻‍</p><h4><strong>1. Double and Tripple mouse click</strong></h4><p>These two were so basic that I was surprised 😯. (But something so obvious for some might not be obvious for others)</p><p><strong>Double click anywhere inside a word to select </strong>entire word. This seems much better than <br><em>“go to start of word, click and scroll all the way till end of the word”<br></em>except if you are selecting multiple words at once, where I often find keyboard shortcut better.</p><p><strong>Tripple click inside a line to select entire current line</strong></p><p>I just have these 2️⃣related to mouse 🐁.</p><h3>Keyboard Shortcuts</h3><h4>2. The very basic ones</h4><p>These are mostly known to everyone, but mentioning them just in case you never thought of using shortcuts before 👶.</p><p><strong>Ctrl + XCut</strong></p><p><strong>Ctrl + C Copy</strong></p><p><strong>Ctrl + V Paste</strong></p><p><strong>Ctrl + T Browser shortcut to open a new tab</strong></p><p><strong>Ctrl + N Open new file/new window depending on application</strong></p><p><strong>Ctrl + S Save current thing</strong></p><p><strong>And not to miss out lock screen shortcuts</strong></p><p><strong>Win + L Windows</strong></p><p><strong>Ctrl + CMD + Q Mac</strong></p><p><strong>Quite important</strong> when you are working in an office space and need to always lock screen before leaving your desk 🥤🍽️.</p><h4>3. The ones I want everyone to use</h4><p>Use these when you want to move cursor within a piece of text using left/right arrow keys faster ️🏃‍♂, by jumping word by word instead of character by character.</p><p><strong>Ctrl + Left/Right Arrow Move cursor word by word</strong></p><p>For normal selection, you use <strong>Shift + Arrow</strong> keys. For jumping word by word, again just add <strong>Ctrl</strong> to the mix</p><p><strong>Shift + Ctrl + Arrow Keys Select word by word</strong></p><h4>4. 🪟Window management shortcuts</h4><p>I use this so much that after a while, <strong>Ctrl</strong>and <strong>Alt</strong> keys on my keyboard sometimes look like this after a while</p><p><strong>Alt + Tab</strong> <strong>⏩Cycle between open applications</strong></p><p><strong>Alt + Shift + Tab ⏪ Reverse cycle between open applications</strong></p><p>If you are new, you might find above shortcuts irritating or useless, but</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*eDZQJn6BKrgH0DBzwpr4sA.gif" /></figure><p>soon it’ll become automatic just like driving. And it obviously makes things much faster.</p><p>Mac also has this good shortcut to switch between instances of the same application, which I don’t think is possible on windows (maybe works with some custom shortcuts 🤷🏻‍♂️). I use this a lot when(always) I have multiple windows open on IntelliJ or V S Code.</p><p><strong>CMD + ` (Command + backtick) ⏩</strong></p><p><strong>CMD + Shift + ` ⏪</strong></p><p>Cycle between tabs of an application like Brower, Code Editor, IDE etc.</p><p><strong>Ctrl + Tab Forward ▶️</strong></p><p><strong>Ctrl + Shift + Tab ◀ ️Backward</strong></p><p>In editors it will cycle you through open files, on brower throught open tabs and like that.</p><h4>5. Box selection</h4><p>Well this varies from edior to editor, but I’ve just kept it here so that you can search “box select in xyz” and learn about it.</p><p>This is super useful if you are writing code🧑🏻‍💻!! Trust me 🙂</p><p>⚠️️️⚠️️️ ️️️Valid till keyboards become obsolete ️️⚠️⚠️</p><p>Say 👋🏻👋🏻 on <a href="https://in.linkedin.com/in/leangaurav">Linkedin</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf6578d3f303" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type Alias vs Type Definition in Go]]></title>
            <link>https://leangaurav.medium.com/type-alias-vs-type-definition-in-go-84a82a82990?source=rss-8ed82d391e34------2</link>
            <guid isPermaLink="false">https://medium.com/p/84a82a82990</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[leangaurav]]></dc:creator>
            <pubDate>Mon, 11 Sep 2023 04:47:26 GMT</pubDate>
            <atom:updated>2023-09-11T15:49:37.686Z</atom:updated>
            <content:encoded><![CDATA[<h3>Type Alias vs Type Definition in Go: when to use what</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*AIAQlJA3TgiVdHGNrIJAXQ.gif" /></figure><p>Let’s start coding !!</p><p>Look at the code below and think what it prints. <em>[%T is used to print type info]</em></p><pre>package main<br><br>import &quot;fmt&quot;<br><br>type int1 = int // OPTION-1<br>type int2 int   // OPTION-2<br><br>func main() {<br> var i1 int1<br> var i2 int2<br> fmt.Printf(&quot;%T, %T&quot;, i1, i2)<br>}</pre><p><strong>Output</strong></p><pre>int, main.int2</pre><p><a href="https://go.dev/play/p/q_Gs9JeqRam"><strong>source</strong></a></p><p>Interestingly, <strong><em>i1</em></strong> prints <strong><em>int </em></strong>and <strong><em>i2</em> </strong>prints <strong><em>main.int2</em>. <br></strong>Why we see this output ?</p><figure><img alt="Think !!" src="https://cdn-images-1.medium.com/max/268/1*u4BzqswJFudoHtihprJkOA.gif" /></figure><p><strong><em>i1</em></strong> is an alias. Alias is a second name for an exising type and it’s just like replacing all occurences of <strong><em>int1</em></strong> with int.<br>Whereas <strong><em>int2</em></strong> is a type definition. Notice the output says: “main.int2”. What this means is <strong><em>int2</em></strong> is a new type.</p><h3>What’s the difference ?</h3><p>We need to look at it from following angles:</p><ol><li><strong>Behavior of operations wrt the new type</strong></li></ol><p>We want to test if the new types behave exactly like the original type <strong><em>int</em></strong>. To do this, we try some operations that are supported by int type.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>type int1 = int // OPTION-1<br>type int2 int   // OPTION-2<br><br>func main() {<br> var i1 int1<br> var i2 int2<br><br> // Check if integer operations works<br> i1 += 10<br> i2 += 10<br><br> i1 -= 5<br> i2 -= 5<br><br> // check if the new type needs an explicit type conversion<br> var i3 int = i1<br> var i4 int = i2<br><br> fmt.Println(i1, i2, i3, i4)<br>}</pre><p><strong>Output</strong></p><pre>./prog.go:21:15: cannot use i2 (variable of type int2) as int value in variable declaration<br><br>Go build failed.</pre><p><a href="https://go.dev/play/p/jm0pC3mQ-6P"><strong>source</strong></a></p><p>This is expected based on the output of the first program. The newly defined type cannot be assigned to an <strong><em>int</em></strong> var since <strong><em>i2&#39;s</em></strong> type is not int, it’s <strong><em>main.int2</em></strong> instead. Hence we need an explicit type cast like below and everything would just work fine.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>type int1 = int // OPTION-1<br>type int2 int   // OPTION-2<br><br>func main() {<br> var i1 int1<br> var i2 int2<br><br> // Check if integer operations works<br> i1 += 10<br> i2 += 10<br><br> i1 -= 5<br> i2 -= 5<br><br> // check if the new type needs an explicit type conversion<br> var i3 int = i1<br> var i4 int = int(i2) // NOTICE HERE !!<br><br> fmt.Println(i1, i2, i3, i4)<br>}</pre><p><strong><em>Output</em></strong></p><pre>5 5 5 5</pre><p><strong>2. Defining new operations/methods</strong></p><p>Let’s try to define a method on our newly defined type.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>type int1 = int // OPTION-1<br>type int2 int   // OPTION-2<br><br>func (i int1) ToString() string {<br> return fmt.Sprintf(&quot;%d&quot;, i)<br>}<br><br>func (i int2) ToString() string {<br> return fmt.Sprintf(&quot;%d&quot;, i)<br>}<br><br>func main() {<br>}</pre><p><strong>Output</strong></p><pre>./prog.go:8:7: cannot define new methods on non-local type int</pre><p><a href="https://go.dev/play/p/dXP3hZkyTsV"><strong>source</strong></a></p><p>Again similar to previous example we, the code doesn’t run and we get an error. But this time the <strong>error is for the type alias </strong>instead of the new type defined using type definition.</p><p>Since this operation itself doesn’t work, we remove the method func (i int1) ToString() string and try to run the remaining code.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>type int1 = int // OPTION-1<br>type int2 int   // OPTION-2<br><br>func (i int2) ToString() string {<br> return fmt.Sprintf(&quot;%d&quot;, i)<br>}<br><br>func main() {<br> var i1 int1<br> var i2 int2<br><br> fmt.Println(i1, i2.ToString())<br>}</pre><p><strong>Output</strong></p><pre>0 0</pre><p><strong>3. Assignment operations</strong></p><p>We already saw one error in our second example, where a newly defined type could not be assigned to the original underlying type. Let’s look at the other side now.</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>type int1 = int // OPTION-1<br>type int2 int   // OPTION-2<br><br>func main() {<br> var i1 int1<br> var i2 int2<br><br> const (<br>  c1     = 5  // untyped numeric const<br>  c2 int = 10 // typed numeric const<br> )<br><br> // assign untyped constant<br> i1 = c1<br> i2 = c1<br><br> // assign a typed constant<br> i1 = c2<br> i2 = c2 // LINE-23<br><br> // assign a typed var<br> var i int = 15<br> i1 = i<br> i2 = i // LINE-28<br><br> fmt.Println(i1, i2)<br>}</pre><p><strong>Output</strong></p><pre>./prog.go:23:7: cannot use c2 (constant 10 of type int) as int2 value in assignment<br>./prog.go:28:7: cannot use i (variable of type int) as int2 value in assignment<br><br>Go build failed.</pre><p><a href="https://go.dev/play/p/f4kTjcb8HiH">source</a></p><p>The error messages are pretty much self explanatory.</p><p>However you must notice that i2 = c2 fails while i2 = c1 doesn’t. That’s because go does a strict type matching. So for typed constants(c2) or for typed variables (line 28), type must match whereas for untyped constants (c1), type can be inferred within the expression if it’s compatible.</p><h3>Applications</h3><p><strong>Type Alias</strong></p><p>It can simply be used to define another name (alias 😝) which can be used in place of the orignal name. When would you do that ?<br>When you don’t like the original type name, maybe too vebose🙈.<br>There can actually be valid reasons for doing this, see the “reading material” at the end.</p><p>or maybe you want to tell the world that you have written this code 🤣</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>type gaurav = int<br><br>func main() {<br> var leangaurav gaurav<br> leangaurav++<br> fmt.Println(leangaurav)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*5RI_SoWhwtEuhMEJ3LD_QQ.gif" /><figcaption><a href="https://go.dev/play/p/Xl1y-uXiGjd">https://go.dev/play/p/Xl1y-uXiGjd</a></figcaption></figure><p><strong>Type Definition</strong></p><p>There might be other reasons for using type definition, but one of them is using type defintion for <strong>enum </strong>like behavior. Like this example from <a href="https://go.dev/ref/spec#Type_definitions">go spec</a> which is slighly modified for ease of understanding. Go through the spec to read the original code.</p><pre>type TimeZone int<br><br>const (<br>	EST TimeZone = -5<br>	CST TimeZone = -6<br>	MST TimeZone = -7<br>	PST TimeZone = -8<br>)<br><br>func (tz TimeZone) String() string {<br>	return fmt.Sprintf(&quot;GMT%+dh&quot;, tz)<br>}</pre><p><strong>More reading material about type alias and type definition</strong></p><ol><li><a href="https://go.dev/talks/2016/refactor.article">https://go.dev/talks/2016/refactor.article</a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*tVMzP-i11PonbXstxPf-Iw.gif" /><figcaption>that’s all folks!</figcaption></figure><p>Try to play with the examples yourself as there’s much more to explore.</p><p>You can find me on <a href="https://in.linkedin.com/in/leangaurav">Linkedin</a> 👋🏻👋🏻.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84a82a82990" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All about defer statement in golang]]></title>
            <link>https://leangaurav.medium.com/all-about-defer-statement-in-golang-88a5cfb65413?source=rss-8ed82d391e34------2</link>
            <guid isPermaLink="false">https://medium.com/p/88a5cfb65413</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[leangaurav]]></dc:creator>
            <pubDate>Fri, 21 Apr 2023 13:19:19 GMT</pubDate>
            <atom:updated>2025-04-25T23:57:07.246Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to use defer statement in golang</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XEc-TqSdI3lsGbna6BJYVQ.jpeg" /></figure><p>Defer statement is pretty simple to understand. But it has it’s <a href="https://en.wikipedia.org/wiki/Gotcha_(programming)">gotchas</a>. Mostly we learn from our mistakes, in this guide, you’ll learn from my mistakes. This is a pure code based walkthrough, cos that’s how you learn best. So try to run and play with the linked go playground code examples on your own. Lets get started.</p><h3>First Thing: What is defer 🤔 ?</h3><blockquote>A defer statement defers the execution of a function<strong> until the surrounding function returns</strong>.</blockquote><blockquote>The deferred call’s arguments are<strong> evaluated immediately</strong>, but the function call is not executed until the surrounding function returns.</blockquote><blockquote>Source: <a href="https://go.dev/tour/flowcontrol/12">https://go.dev/tour/flowcontrol/12</a></blockquote><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br> defer fmt.Println(&quot;world&quot;)<br><br> fmt.Println(&quot;hello&quot;)<br>}</pre><p>Output</p><pre>hello<br>world</pre><p>Defer is simply a convenience that lets you defer/push cleanup operations for later execution.</p><p>Consider this example of locking and unlocking a</p><p>Defer helps you keep resource allocation and cleanup together. Leaving less space for unintentional bugs. Other languages too have their own ways of doing this, but in go it’s called defer.</p><h3>How defer works ?</h3><h4>1. Defer uses stack order evaluation 📚</h4><p>See below example with multiple defers in same function.</p><p><a href="https://go.dev/play/p/6ixm52xVWDE">https://go.dev/play/p/6ixm52xVWDE</a></p><pre>// Predict the order<br>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br> defer fmt.Println(&quot;1&quot;) // Push to stack<br> defer fmt.Println(&quot;2&quot;) // Push to stack<br> defer fmt.Println(&quot;3&quot;) // Push to stack<br>}</pre><p><strong>Output</strong></p><pre>3<br>2<br>1</pre><p>Since defer uses stack, all Println calls get pushed to stack.</p><pre> __________________<br>| fmt.Println(&quot;3&quot;) |  // Top of stack<br>|------------------|<br>| fmt.Println(&quot;2&quot;) |<br>|------------------|<br>| fmt.Println(&quot;1&quot;) |  // Bottom<br> ------------------</pre><p>Once the main() or enclosing function completes, each item is popped of stack and executed. Hence the output in reverse order of defer statements.</p><h4><strong>2. </strong>Defer statements in a loop ➰</h4><p>Predict output of below code.</p><p><a href="https://go.dev/play/p/gqQsX0TYPh8">https://go.dev/play/p/gqQsX0TYPh8</a></p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br>)<br>func main() {<br> for i := 0; i &lt; 5; i += 1 {<br>  defer fmt.Println(&quot;loop&quot;)<br> }<br> fmt.Println(&quot;main&quot;)<br>}</pre><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>.</p><p>Output</p><pre>main<br>loop<br>loop<br>loop<br>loop<br>loop</pre><p>Quite expected right !! Since defer pushes function execution to function call stack, this means all the loop’s get printed after enclosing function ends.</p><h4><strong>3. Arguments to deferred function are evaluated immediately 🐱‍🏍</strong></h4><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br>)<br><br>func main() {<br> defer fmt.Println(&quot;Defer&quot;, time.Now()) // What does this print ?<br><br> fmt.Println(&quot;Before&quot;, time.Now())<br> time.Sleep(time.Second)<br> fmt.Println(&quot;After&quot;, time.Now())<br>}</pre><p>Output</p><pre>Before 2009-11-10 23:00:00 +0000 UTC m=+0.000000001<br>After 2009-11-10 23:00:01 +0000 UTC m=+1.000000001<br>Defer 2009-11-10 23:00:00 +0000 UTC m=+0.000000001</pre><p>Notice that even though defered statement will get executed after fmt.Println(“After”, time.Now()) , still it prints lesser value of time.</p><p><strong>Solution:</strong> Wrap in a function. This is a common pattern you should be aware of to avoid such issues.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br>)<br><br>func main() {<br> <br> defer func() {<br>   fmt.Println(&quot;Defer&quot;, time.Now()) // What does this print now ?<br> } () // Remember to call ()<br><br> fmt.Println(&quot;Before&quot;, time.Now())<br> time.Sleep(time.Second)<br> fmt.Println(&quot;After&quot;, time.Now())<br>}</pre><p>Output</p><pre>Before 2009-11-10 23:00:00 +0000 UTC m=+0.000000001<br>After 2009-11-10 23:00:01 +0000 UTC m=+1.000000001<br>Defer 2009-11-10 23:00:01 +0000 UTC m=+1.000000001</pre><p>Also guess this one yourself<br><a href="https://go.dev/play/p/SXF6kV7jJpM">https://go.dev/play/p/SXF6kV7jJpM</a></p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br>)<br><br>func main() {<br> i := 0<br> defer func(val int) {<br>  fmt.Println(&quot;Defer&quot;, val) // What does this print<br> }(i)<br><br> i += 1<br> fmt.Println(&quot;i = &quot;, i)<br>}</pre><h4><strong>4. Variable/Local state capture</strong></h4><p>What does example print 🙈<br><a href="https://go.dev/play/p/pyPfLyQ7UMw">https://go.dev/play/p/pyPfLyQ7UMw</a></p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br>)<br><br>func main() {<br> for i := 0; i &lt; 5; i += 1 {<br>  defer fmt.Println(&quot;Count&quot;, i) // (0 1 2 3 4) or (4 3 2 1 0) or (4 4 4 4 4) ?<br> }<br> fmt.Println(&quot;main&quot;)<br>}</pre><p>.</p><p>.</p><p>.</p><p>.</p><p>Output</p><pre>main<br>Count 4<br>Count 3<br>Count 2<br>Count 1<br>Count 0</pre><p>No tricks here 🎃. Simple stuff. Since defer evaluates args when you write defer, each call in the loop captures the current value and pushes a copy onto stack.</p><p>Well… what do you think this prints<br><a href="https://go.dev/play/p/lRboy_DdDu_9">https://go.dev/play/p/lRboy_DdDu_9</a></p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br>)<br><br>func main() {<br> count := 0<br><br> for i := 0; i &lt; 5; i += 1 {<br>  count += 1<br><br>  defer func() { // Notice the enclosing function here<br>   fmt.Println(&quot;Count&quot;, count) <br>  }()<br><br> }<br><br> fmt.Println(&quot;main&quot;)<br>}</pre><p>Maybe you didn’t expect this, but it’s true</p><pre>main<br>Count 5<br>Count 5<br>Count 5<br>Count 5<br>Count 5</pre><p>If this kind of behavior is a problem for your use case. Think how to fix this. Hint, pass count as argument 😉.</p><p><strong>Lets do some nested calls. <br></strong>What does this print ?<br><a href="https://go.dev/play/p/TV1fyqNCuBX">https://go.dev/play/p/TV1fyqNCuBX</a></p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br>)<br><br>func dummy(msg string) {<br> defer fmt.Println(&quot;dummy defer&quot;, msg)<br> fmt.Println(&quot;dummy&quot;, msg)<br>}<br><br>func main() {<br><br> dummy(&quot;1&quot;)<br> defer dummy(&quot;2&quot;)<br> fmt.Println(&quot;main&quot;)<br>}</pre><p>Output</p><pre>dummy 1<br>dummy defer 1<br>main<br>dummy 2<br>dummy defer 2</pre><h3>Defer usage patterns</h3><h3>1. Interleave defer correctly when calling functions that return an error</h3><h4><strong>Problem:</strong></h4><p>Look at below code which doesn’t use defer.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;os&quot;<br>)<br><br>func doSomething(_ *os.File) {<br>}<br><br>func main() {<br><br> file, err := os.Create(&quot;temp.txt&quot;) // 1. Function Call<br> if err != nil {                    // 2. Handle error               <br>  fmt.Println(&quot;Error creating file&quot;, err)<br>  return<br> }<br><br> doSomething(file)<br><br> file.Close()                       // 3. Free up resource<br>}</pre><p>Do you see any problem here ? 👀</p><p>The issue is if doSomething crashes for some reson, file.Close never runs. Consider this running as a http handler. Each call where doSomething crashes, leaks a resource 💣.</p><h4><strong>The Fix ⚒</strong></h4><p>We should defer here to close the file after opening it</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;os&quot;<br>)<br><br>func doSomething(_ *os.File) {<br>}<br><br>func main() {<br> file, err := os.Create(&quot;temp.txt&quot;) // allocate<br> defer file.Close() // free<br> if err != nil { // error check<br>  fmt.Println(&quot;Error creating file&quot;, err)<br>  return<br> }<br><br> doSomething(file)<br><br> <br>}</pre><p>Wait 🛑🤚🏻🛑.<br>Is this really correct? <strong>NO</strong></p><p>What happens if os.Create fails ? file will likely be nil and file.Close() will crash your code.</p><p>So the right pattern to<strong> defer cleanup actions</strong> is immediately<strong> after error check.</strong></p><h4><strong>The Real Fix 👷🏻‍♂️</strong></h4><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;os&quot;<br>)<br><br>func doSomething(_ *os.File) {<br>}<br><br>func main() {<br> file, err := os.Create(&quot;temp.txt&quot;)      // 1. Function Call<br> if err != nil {                         // 2. Handle error<br>  fmt.Println(&quot;Error creating file&quot;, err)<br>  return<br> }<br> defer file.Close()                      // 3. Defer cleanup ops<br><br> doSomething(file)<br><br>}</pre><p>So the correct order always looks like</p><ol><li>Create resource</li><li>Do error check and return</li><li>defer resource cleanup</li></ol><p>Before we move ahead, try to run the first example with some invalid file name to try to crash it and see what happens… well… it doesn’t crash 😆. <br>No 🎇🎆🔥. <br>No segmentation fault.</p><p>Here I try passing an empty file name. <a href="https://go.dev/play/p/Z5Ef1Bh69g_E">https://go.dev/play/p/Z5Ef1Bh69g_E</a></p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;os&quot;<br>)<br><br>func doSomething(_ *os.File) {<br>}<br><br>func main() {<br> file, err := os.Create(&quot;&quot;) // pass empty file here<br> defer file.Close()         <br> if err != nil {<br>  fmt.Println(&quot;Error creating file&quot;, err)<br>  return<br> }<br><br> doSomething(file)<br><br>}</pre><p>It works perfectly fine and prints this:</p><pre>Error creating file open : no such file or directory</pre><p>If you are thinking why, check out the implementation of Close: <a href="https://cs.opensource.google/go/go/+/refs/tags/go1.20.3:src/os/file_posix.go;l=21">https://cs.opensource.google/go/go/+/refs/tags/go1.20.3:src/os/file_posix.go;l=21</a></p><p>Notice the nil check there. But don’t expect things to always be like this and always use defer correctly.</p><p>Perfect !! 👌🏻 Let’s move on.</p><h3>2. Working with WaitGroups</h3><p>This is really interesting. Read line by line carefully, then try running this code yourself.<br><a href="https://go.dev/play/p/lbxLH_4tK5_h">https://go.dev/play/p/lbxLH_4tK5_h</a></p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br>)<br><br>var i = 0<br><br>func incr() {<br> i += 1<br>}<br><br>// +100,000<br>func incrLoop() {<br> for i := 1; i &lt;= 100000; i += 1 {<br>  incr()<br> }<br>}<br><br>func main() {<br> var wg sync.WaitGroup<br><br> // +100,000<br> wg.Add(1) // This needs to be outside. <br> go func() {<br>  defer wg.Done()<br>  incrLoop()<br> }()<br><br> // another +100,000 in parallel<br> wg.Add(1)<br> go func() {<br>  defer wg.Done()<br>  incrLoop()<br> }()<br><br> wg.Wait()<br> fmt.Println(&quot;i=&quot;, i) //  if everything works, i should be 200 000<br>}</pre><p>What did you get ?</p><pre>i= 200000</pre><p>really ?? 🤷🏻 not possible except if you are really lucky 🤞🏻</p><p>Run ️a couple more times till you start seeing things like this</p><pre>i= 141663</pre><p>or</p><pre>i= 156991</pre><p>or anything which isn’t 200,000.</p><p>So the problem isn’t with waitgroup, we are using it perfectly fine. Try removing wait group and you’ll start seeing i= 0 .</p><p>Let’s fix the issue in the next one.</p><blockquote>Read more about waitgroup patterns and how to use it properly <a href="https://medium.com/@leangaurav/common-mistakes-when-using-golangs-sync-waitgroup-88188556ca54">here</a>.</blockquote><h3>3. Working with mutex</h3><p>So the problem with previous code was… incr() gets called from two functions/goroutines in parallel. This is a classic problem with a classic solution.<br><a href="https://go.dev/play/p/SKbmJW1nuRy">https://go.dev/play/p/SKbmJW1nuRy</a></p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br>)<br><br>var i = 0<br>var mu sync.Mutex // We added this<br><br>func incr() {<br> mu.Lock() // + this<br> defer mu.Unlock() // + this<br> i += 1<br>}<br><br>// +100,000<br>func incrLoop() {<br> for i := 1; i &lt;= 100000; i += 1 {<br>  incr()<br> }<br>}<br><br>func main() {<br> var wg sync.WaitGroup<br><br> // +100,000<br> wg.Add(1) <br> go func() {<br>  defer wg.Done()<br>  incrLoop()<br> }()<br><br> // another +100,000 in parallel<br> wg.Add(1)<br> go func() {<br>  defer wg.Done()<br>  incrLoop()<br> }()<br><br> wg.Wait()<br> fmt.Println(&quot;i=&quot;, i) <br>}</pre><p>This correctly prints</p><pre>i= 200000</pre><p>Problem solved 🙌🏻</p><p>There can be better ways of solving this, but this works as a good enough example.</p><p>More examples coming soon.</p><p>Find me on <a href="https://in.linkedin.com/in/leangaurav">Linkedin</a> 👋🏻.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88a5cfb65413" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching: What to choose Redis or Memcached]]></title>
            <link>https://leangaurav.medium.com/caching-what-to-choose-redis-or-memcached-b6a96ba612a4?source=rss-8ed82d391e34------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6a96ba612a4</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[memcached]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[leangaurav]]></dc:creator>
            <pubDate>Wed, 01 Mar 2023 16:55:55 GMT</pubDate>
            <atom:updated>2023-03-01T16:55:55.753Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a short post just to quickly compare the two on high level and direct you to other good resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vLIRiAyw5Izi4hBski3jWA.jpeg" /></figure><p><strong>What is Memcached?<br></strong> <a href="https://memcached.org/">https://memcached.org/</a></p><blockquote>Memcached is an in-memory<strong> key-value store</strong> for small chunks of arbitrary data <strong>(strings, objects)</strong> from results of database calls, API calls, or page rendering.</blockquote><p><strong>What is Redis?</strong><br><a href="https://redis.io/docs/about/">https://redis.io/docs/about/</a></p><blockquote>Redis is an open source (BSD licensed), in-memory data structure store used as a database, cache, message broker, and streaming engine. Redis provides <a href="https://redis.io/docs/data-types/">data structures</a> such as <a href="https://redis.io/docs/data-types/strings/">strings</a>, <a href="https://redis.io/docs/data-types/hashes/">hashes</a>, <a href="https://redis.io/docs/data-types/lists/">lists</a>, <a href="https://redis.io/docs/data-types/sets/">sets</a>, <a href="https://redis.io/docs/data-types/sorted-sets/">sorted sets</a> with range queries, <a href="https://redis.io/docs/data-types/bitmaps/">bitmaps</a>, <a href="https://redis.io/docs/data-types/hyperloglogs/">hyperloglogs</a>, <a href="https://redis.io/docs/data-types/geospatial/">geospatial indexes</a>, and <a href="https://redis.io/docs/data-types/streams/">streams</a>. Redis has built-in <a href="https://redis.io/topics/replication">replication</a>, <a href="https://redis.io/commands/eval">Lua scripting</a>, <a href="https://redis.io/docs/reference/eviction/">LRU eviction</a>, <a href="https://redis.io/topics/transactions">transactions</a>, and different levels of <a href="https://redis.io/topics/persistence">on-disk persistence</a>, and provides high availability via <a href="https://redis.io/topics/sentinel">Redis Sentinel</a> and automatic partitioning with <a href="https://redis.io/topics/cluster-tutorial">Redis Cluster</a>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*m_3AMNIVokh1HW3EaQmvZg.jpeg" /><figcaption>Taken from AWS</figcaption></figure><p>Since posts become outdated over time jump to <a href="https://aws.amazon.com/elasticache/redis-vs-memcached/">AWS and read it directly</a>. Since it can be assumed that cloud vendors have to keep their documentation up to date.</p><h4><strong>Summary</strong></h4><ul><li>Memcached is simple Key-Value store for strings and objects</li><li>Redis is memached + many things</li><li>Both support common caching use cases like keys with TTL etc.</li><li>Max number of keys:<br>Redis: 2³²Refer <a href="https://redis.io/docs/getting-started/faq/#:~:text=Redis%20can%20handle%20up%20to,can%20hold%202%5E32%20elements.">this </a>for updated info<br>Memcached: Need reference.</li><li>Memcached max key size: 250 bytes, max value size: 1MB default + configurable</li><li>Redis max key size: 512 MB</li></ul><h3>Other Points to Note</h3><h4>Single vs MultiThreaded</h4><p>Redis internally runs on a single thread (makes implementation easy).<br>Memcached can run on multiple cores.</p><p>Hence Memcached can have better performance. Look at benchmarks or run your own for your workload.</p><h4>Simple vs Complex 🎯</h4><p>If you need a simple Key Value store: go for Memcached.<br>Need complex data structures: go for Redis.<br>You want to store your key value data somewhere. Use whatever your organization already uses. Doesn’t matter.</p><h4>Coming to practical usage (my perspective ❗)</h4><p>I see both Redis and Memcahed being used at places without issues. Mainly I have seen it used as a key value store or some sort of caching application. Also Redis pub-sub for live streams.<br>However Redis seems to have data loss issues in case of network partitions. Read these:</p><ol><li><a href="https://aerospike.com/when-to-use-aerospike-vs-redis/">https://aerospike.com/when-to-use-aerospike-vs-redis/</a></li><li><a href="https://redis.io/docs/management/sentinel/">https://redis.io/docs/management/sentinel/</a></li><li><a href="https://aphyr.com/posts/283-jepsen-redis">https://aphyr.com/posts/283-jepsen-redis</a> Old but still relevant I think</li></ol><p>So I won’t think of using Redis as a Datastore.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6a96ba612a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Common mistakes when using golang’s sync.WaitGroup]]></title>
            <link>https://leangaurav.medium.com/common-mistakes-when-using-golangs-sync-waitgroup-88188556ca54?source=rss-8ed82d391e34------2</link>
            <guid isPermaLink="false">https://medium.com/p/88188556ca54</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[sync]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[leangaurav]]></dc:creator>
            <pubDate>Tue, 28 Feb 2023 04:47:42 GMT</pubDate>
            <atom:updated>2026-06-10T16:58:54.423Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bN3NyjBRJokduuQnInEsog.jpeg" /></figure><p>This can be your WaitGroup crash course. Lets start step by step.</p><p><em>Read through the end or else you might end up learning something wrong and blame me for it </em>😝</p><blockquote><em>Since we are going to use defer statement in the code examples, might be good to go through </em><a href="https://leangaurav.medium.com/all-about-defer-statement-in-golang-88a5cfb65413"><strong><em>How to use defer statement in golang</em></strong></a></blockquote><blockquote><em>I hope this will save your precious time 😀… consider hitting 👏 at the end. !! You can appreciate my efforts… </em><a href="https://www.buymeacoffee.com/leangaurav"><strong><em>buy me a tea</em></strong></a><strong><em> </em></strong><em>☕.</em></blockquote><h4>0. Example Worker</h4><p>Below is a simple example with a worker function to print a message. No concurrency 🍰.</p><pre>// https://go.dev/play/p/vWL9zhQC1LT<br>package main<br><br>import (<br> &quot;fmt&quot;<br>)<br><br>func worker(msg string) {<br> fmt.Println(&quot;Worker&quot;, msg)<br>}<br><br>func main() {<br> worker(&quot;w1&quot;)<br> fmt.Println(&quot;exiting&quot;)<br>}</pre><p><strong>Output:</strong></p><pre>Worker w1<br>exiting</pre><h4>1. More workers 🐜🐜🐜</h4><pre>// https://go.dev/play/p/qE-UT_NM5Q3<br>package main<br><br>import (<br> &quot;fmt&quot;<br>)<br><br>func worker(msg string) {<br> fmt.Println(&quot;Worker&quot;, msg)<br>}<br><br>func main() {<br> worker(&quot;w1&quot;)<br> worker(&quot;w2&quot;)<br> worker(&quot;w3&quot;)<br> fmt.Println(&quot;exiting&quot;)<br>}</pre><p><strong>Output:</strong></p><pre>Worker w1<br>Worker w2<br>Worker w3<br>exiting</pre><h4>2. Sprinkle some concurrency 🧂</h4><pre>// https://go.dev/play/p/qE-UT_NM5Q3<br>package main<br><br>import (<br> &quot;fmt&quot;<br>)<br><br>func worker(msg string) {<br> fmt.Println(&quot;Worker&quot;, msg)<br>}<br><br>func main() {<br> go worker(&quot;w1&quot;)<br> go worker(&quot;w2&quot;)<br> go worker(&quot;w3&quot;)<br> fmt.Println(&quot;exiting&quot;)<br>}</pre><p><strong>Output:</strong></p><pre>Worker w1<br>Worker w2<br>Worker w3<br>exiting</pre><p>or maybe</p><pre>Worker w1<br>exiting</pre><p>or</p><pre>Worker w1<br>Worker w2<br>exiting</pre><p>or even</p><pre>Worker w2<br>Worker w1<br>exiting</pre><p>Honestly we don’t know 🤷🏻‍♂️</p><h4>3. Fix with a WaitGroup 🔧</h4><p>To ensure we wait for all workers to complete. WaitGroup has a <a href="https://pkg.go.dev/sync#WaitGroup"><strong><em>simple API</em></strong></a><strong><em>. </em></strong>We are also using <a href="https://leangaurav.medium.com/all-about-defer-statement-in-golang-88a5cfb65413"><strong><em>defer</em></strong></a><strong><em> </em></strong>keyword now<strong><em>.</em></strong></p><ul><li><strong><em>Add(int)</em></strong> adds delta, which may be negative, to the WaitGroup counter.</li><li><strong><em>Done()</em></strong><em> </em>decrements the WaitGroup counter by one.</li><li><strong><em>Wait()</em></strong> blocks until the WaitGroup counter is zero.</li></ul><pre>// https://go.dev/play/p/r-4JT1upJQf<br>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br>)<br><br>var wg sync.WaitGroup<br><br>func worker(msg string) {<br> wg.Add(1)<br> defer wg.Done()<br> fmt.Println(&quot;Worker&quot;, msg)<br>}<br><br>func main() {<br> go worker(&quot;w1&quot;)<br> go worker(&quot;w2&quot;)<br> go worker(&quot;w3&quot;)<br><br> fmt.Println(&quot;waiting&quot;)<br> wg.Wait()<br> fmt.Println(&quot;exiting&quot;)<br>}</pre><p><strong>Output:</strong></p><pre>waiting<br>Worker w1<br>Worker w2<br>Worker w3<br>exiting</pre><p>or</p><pre>Worker w1<br>waiting<br>Worker w2<br>Worker w3<br>exiting</pre><p>or</p><pre>Worker w2<br>waiting<br>Worker w1<br>Worker w3<br>exiting</pre><p>or something else. But we have a guarantee. Guarantee that exiting is always printed after all lines starting with Worker have been printed.</p><h4>4. Passing WaitGroup as argument</h4><p>Often.. or mostly we don’t create global variables. We create function scoped variables. Lets see how our code changes when we pass WaitGroup to a function.</p><pre><br>// https://go.dev/play/p/QoCJIbPkXkC<br>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br>)<br><br>func worker(msg string, wg sync.WaitGroup) {<br> wg.Add(1)<br> defer wg.Done()<br> fmt.Println(&quot;Worker&quot;, msg)<br>}<br><br>func main() {<br> var wg sync.WaitGroup<br> go worker(&quot;w1&quot;, wg)<br> go worker(&quot;w2&quot;, wg)<br> go worker(&quot;w3&quot;, wg)<br><br> fmt.Println(&quot;waiting&quot;)<br> wg.Wait()<br> fmt.Println(&quot;exiting&quot;)<br>}</pre><p>Notice the wg declaration moving inside main and our worker now accepts the WaitGroup as second argument.</p><p><strong>Output:</strong></p><pre>waiting<br>exiting</pre><p>Not quite expected right !!</p><p><strong>Reason:</strong> If you carefully notice the definition of WaitGroup methods carefully, you will see notice a pointer receiver. And WaitGroup is not an interface with an implementation using pointer receiver💡.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*JBO2RnkOSvR6Q9l73KEoMw.png" /></figure><p>This means, if we pass the WaitGroup without a pointer, a copy gets created.</p><p>Also notice</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*mMAhdD4idWygW8yPLsJbOg.png" /></figure><h4>5. Lets fix it 💪🏻</h4><pre>// https://go.dev/play/p/QoCJIbPkXkC<br>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br>)<br><br>// Notice the * here<br>func worker(msg string, wg *sync.WaitGroup) {<br> wg.Add(1)<br> defer wg.Done()<br> fmt.Println(&quot;Worker&quot;, msg)<br>}<br><br>func main() {<br> var wg sync.WaitGroup<br> go worker(&quot;w1&quot;, &amp;wg)<br> go worker(&quot;w2&quot;, &amp;wg)<br> go worker(&quot;w3&quot;, &amp;wg)<br><br> fmt.Println(&quot;waiting&quot;)<br> wg.Wait()<br> fmt.Println(&quot;exiting&quot;)<br>}</pre><p>Get Ready 🎇🎉🎆🎉🎇</p><p><strong>Output:</strong></p><pre>waiting<br>Worker w1<br>Worker w2<br>Worker w3<br>exiting</pre><p>Do you really get above output ?? Eh.. fooled by concurrency.</p><p>Run it enough times and you will get this</p><pre>waiting<br>exiting</pre><p>Or something else weird.</p><p>But wait why.. what’s the problem 😵</p><h4>6. Enlightenment 🧠</h4><p>Problem is not with the Waitgroup or the reference. Problem is in the ordering.</p><p>Notice the two statements wg.Add(1)and defer wg.Done() are written inside the go routine and not in the caller. So it is possible that the caller starts the go routine.. infact all go routines but none of them starts execution till we reach the line wg.Wait() . All go routines are waiting to execute their first statement wg.Add(1) while the main thread continues till end.</p><p>Wait !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</p><p>How the hell did our third example <strong>“2. Add some concurrency 🧂” </strong>work then 🙄</p><p>To answer that yourself, run it a couple times till you see the magic happen yourself. And our third example is logically incorrect and doesn’t gurantee execution of all workers.</p><p><strong>What’s the fix ?</strong><br>It’s a common construct you’ll find in go code. Which looks something like this</p><pre>// https://go.dev/play/p/QoCJIbPkXkC<br>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br>)<br><br>func worker(msg string) {<br> fmt.Println(&quot;Worker&quot;, msg)<br>}<br><br>func main() {<br> var wg sync.WaitGroup<br><br> wg.Add(1)<br> go func() {<br>  defer wg.Done()<br>  worker(&quot;w1&quot;)<br> }()<br><br> wg.Add(1)<br> go func() {<br>  defer wg.Done()<br>  worker(&quot;w2&quot;)<br> }()<br><br> wg.Add(1)<br> go func() {<br>  defer wg.Done()<br>  worker(&quot;w3&quot;)<br> }()<br><br> fmt.Println(&quot;waiting&quot;)<br> wg.Wait()<br> fmt.Println(&quot;exiting&quot;)<br>}</pre><p>Get Ready 🎇🎉🎆🎉🎇</p><p><strong>Output:</strong></p><pre>waiting<br>Worker w1<br>Worker w2<br>Worker w3<br>exiting</pre><p>Notice the theme</p><pre> wg.Add(1)<br> go func() {<br>  defer wg.Done()<br>  worker(&quot;w1&quot;)<br> }()</pre><p>wg.Add(1) appears before entering go routine</p><p>defer wg.Done() is the first statement in the go routine.</p><p>These 2 things ensure proper termination of our concurrent workers.</p><p>Also notice a couple more important things:</p><ol><li><em>we no longer need to pass WaitGroup to the Worker</em></li><li><em>the caller has ownership of </em><em>wg and takes care of cleanup</em></li><li><em>worker only contains core logic and doesn’t have to deal with any concurrency constructs</em></li></ol><p>Phew 😅<br>That’s most of it.</p><h4>7. Can we do better ?</h4><p>There can be just different ways of expressing above code using loops. That’s how we see it in practice as well. Below is an example using a loop to spawn three workers.</p><pre>// https://go.dev/play/p/0UiybqXphC0<br>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br>)<br><br>func worker(msg string) {<br> fmt.Println(&quot;Worker&quot;, msg)<br>}<br><br>func main() {<br> var wg sync.WaitGroup<br><br> for i := 1; i &lt;= 3; i++ {<br><br>  wg.Add(1)<br>  go func() {<br>   defer wg.Done()<br>   worker(fmt.Sprintf(&quot;w%d&quot;, i))<br>  }()<br><br> }<br><br> fmt.Println(&quot;waiting&quot;)<br> wg.Wait()<br> fmt.Println(&quot;exiting&quot;)<br>}</pre><h4>8. Can we do even better ?</h4><blockquote>Thanks <a href="https://medium.com/u/68bbbe428389">D Raehal</a> for commenting</blockquote><p>Yes. Why do something yourself which the standard library already offers. So we will use this function which does what we want and a bit more to make things safer. Standard library stuff is always better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uv8HNJKK7bBPPLoPMH9Kfg.png" /></figure><p>So our updated code looks pretty simple with all the things handled. Check <a href="https://cs.opensource.google/go/go/+/refs/tags/go1.26.4:src/sync/waitgroup.go;l=236">here</a> for the implementation of Go().</p><pre>// https://go.dev/play/p/OjZUdFAZkM1<br>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br>)<br><br>func worker(msg string) {<br> fmt.Println(&quot;Worker&quot;, msg)<br>}<br><br>func main() {<br> var wg sync.WaitGroup<br><br> for i := 1; i &lt;= 3; i++ {<br>  wg.Go(func() { // everything is taken care by Go()<br>   worker(fmt.Sprintf(&quot;w%d&quot;, i))<br>  })<br> }<br><br> fmt.Println(&quot;waiting&quot;)<br> wg.Wait()<br> fmt.Println(&quot;exiting&quot;)<br>}</pre><h4><strong>Key takeaways</strong></h4><ol><li>Avoid passing WaitGroup as argument</li><li>In case WaitGroup has to be passed as argument, do it by reference</li><li>Use the common WaitGroup usage syntax if doing yourself</li></ol><pre>wg.Add(1)         // 1 - Add <br>go func() {       // 2 - The go routine<br>  defer wg.Done() // 3 - Done<br>  someFunc()      // 4 - Your Code<br>} ()              // 5 - Remember to call the goroutine</pre><p>4. Or even better, use the Go() function</p><p>Concurrency is so tricky that still I’m not sure whether I’ve explained all above examples with enough and correct details. We all make mistakes and they help us learn. Have fun and AVOID using concurrent code in production till it’s really necessary.</p><p>Find me on <a href="https://in.linkedin.com/in/leangaurav">Linkedin</a> 👋🏻👋🏻. B<a href="https://www.buymeacoffee.com/leangaurav">uy me a tea</a> ☕</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88188556ca54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bored of jupyter notebooks | Try out some new themes]]></title>
            <link>https://leangaurav.medium.com/bored-of-jupyter-notebooks-try-out-some-new-themes-34ba7fb88d75?source=rss-8ed82d391e34------2</link>
            <guid isPermaLink="false">https://medium.com/p/34ba7fb88d75</guid>
            <category><![CDATA[jupyter]]></category>
            <category><![CDATA[theme-customization]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[themes]]></category>
            <dc:creator><![CDATA[leangaurav]]></dc:creator>
            <pubDate>Wed, 15 Feb 2023 02:23:27 GMT</pubDate>
            <atom:updated>2023-02-15T02:23:27.836Z</atom:updated>
            <content:encoded><![CDATA[<p>Jupyter notebook has a plugin available called <a href="https://github.com/dunovank/jupyter-themes">jupyterthemes</a>.</p><p>This wonderful plugin allows you to customize your notebook theme by installing pre created themes or create your own themes. Lets see how to use some new themes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6zhgk8mzoHslVK604cqnQ.jpeg" /></figure><h4><strong>Step-1: Install jupyter themes</strong></h4><p>Install from a notebook itself</p><pre>!pip install jupyterthemes</pre><p>OR Install from terminal using pip</p><pre>pip install jupyterthemes</pre><p>OR Install from terminal using conda</p><pre>conda install -c conda-forge jupyterthemes</pre><h4>Step-2: List default themes</h4><p>In Terminal</p><pre>jt -l<br><br># OUTPUT<br>#Available Themes:<br>#   chesterish<br>#   grade3<br>#   gruvboxd<br>#   gruvboxl<br>#   monokai<br>#   oceans16<br>#   onedork<br>#   solarizedd<br>#   solarizedl</pre><p>OR In Jupyter Notebook</p><pre>import jupyterthemes as jt<br>jt.get_themes()<br><br># OUTPUT<br>[&#39;chesterish&#39;,<br> &#39;grade3&#39;,<br> &#39;gruvboxd&#39;,<br> &#39;gruvboxl&#39;,<br> &#39;monokai&#39;,<br> &#39;oceans16&#39;,<br> &#39;onedork&#39;,<br> &#39;solarizedd&#39;,<br> &#39;solarizedl&#39;]</pre><h4>Step-3: Preview or try out a theme</h4><p>In a notebook, paste this and execute once</p><pre>import jupyterthemes as jt<br>from jupyterthemes.stylefx import set_nb_theme<br><br>it = iter(jt.get_themes())</pre><p>In next cell paste below code and execute again and again to switch to next theme.</p><pre>theme = next(it)<br>print(&quot;Current Theme: &quot;, theme)<br>set_nb_theme(theme)</pre><h4>Step-4: Apply the theme permanently</h4><p>From terminal run below command. Replace chesterish with your favorite theme.</p><pre>jt -t chesterish</pre><p>OR In a notebook</p><pre>!jt -t chesterish</pre><h4>Step-5: Restart your notebook and enjoy</h4><p>If you wish to get back to the default theme. Remove the theme using below command and restart jupyter notebook.</p><p>Plus if you are using jupyter lab, you can switch themes from menu.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34ba7fb88d75" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>