<?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[Go long with Golang]]></title><description><![CDATA[I am a Python developer currently exploring Go. Join me on my journey as I go long with Golang 👨🏻‍💻🏃🏻]]></description><link>https://golongwithgolang.com</link><generator>RSS for Node</generator><lastBuildDate>Mon, 13 Apr 2026 11:43:43 GMT</lastBuildDate><atom:link href="https://golongwithgolang.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Thread Safety in Golang]]></title><description><![CDATA[A couple of articles ago I wrote about goroutines and how great they are. However, I didn't mention in that article that things can really go bad if you don't use them properly. One of the most important things to keep in mind is that if your gorouti...]]></description><link>https://golongwithgolang.com/thread-safety-in-golang</link><guid isPermaLink="true">https://golongwithgolang.com/thread-safety-in-golang</guid><category><![CDATA[coroutines]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[programming languages]]></category><category><![CDATA[Computer Science]]></category><dc:creator><![CDATA[Pavle Djuric]]></dc:creator><pubDate>Thu, 18 Nov 2021 20:01:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1637265611227/PaHoppo3c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A couple of articles ago I wrote about goroutines and how great they are. However, I didn't mention in that article that things can really go bad if you don't use them properly. One of the most important things to keep in mind is that if your goroutines are going to modify the state of any value stored in a memory address, you need to make them thread safe ( keep in mind that goroutines are actually just cheap threads) .</p>
<p>What exactly do I mean by this. Let me explain through an example:</p>
<pre><code><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"time"</span>
)

<span class="hljs-keyword">type</span> Country <span class="hljs-keyword">struct</span> {
    Name       <span class="hljs-keyword">string</span>
    Continent  <span class="hljs-keyword">string</span>
    Population <span class="hljs-keyword">int32</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">updatePopulation</span><span class="hljs-params">(c *Country, newBorns <span class="hljs-keyword">int32</span>)</span></span> {
    c.Population += newBorns
    fmt.Printf(<span class="hljs-string">"New population of %v is %v\n"</span>, c.Name, c.Population)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    totalStates := <span class="hljs-number">50</span> <span class="hljs-comment">// total number of sources, (US states)</span>
    us := Country{<span class="hljs-string">"USA"</span>, <span class="hljs-string">"North America"</span>, <span class="hljs-number">32000000</span>}
    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt;= totalStates; i++ {
        <span class="hljs-keyword">go</span> updatePopulation(&amp;us, <span class="hljs-keyword">int32</span>(i))
    }
    time.Sleep(time.Second * <span class="hljs-number">5</span>)  <span class="hljs-comment">// this is just so that we don't need channels</span>
}
</code></pre><p>Here is a very simple example. Say we have an application that is tracking the population of countries in real time. The population of a country is dynamic, babies get born all the time, and sadly some people pass away all the time.<br /> The USA is a huge country, which consists of 50 states. So, for the sake of my example, this <code>updatePopulation</code> will simulate a single call to some Census Agency of every state. Since we're in a cheerful mood (and also because I need it to prove my point), we'll only register the newborns and not the departed. </p>
<p>Since we want this app to truly be a real-time tracker, we don't want to make synchronous API calls, we want to make them concurrently, hence the <code>go</code> in front of the <code>updatePopulation</code> function call.</p>
<p>That should do it, right? Let's see the result:</p>
<pre><code><span class="hljs-built_in">New</span> population <span class="hljs-keyword">of</span> USA <span class="hljs-keyword">is</span> <span class="hljs-number">32001199</span>
<span class="hljs-built_in">New</span> population <span class="hljs-keyword">of</span> USA <span class="hljs-keyword">is</span> <span class="hljs-number">32001030</span>
<span class="hljs-built_in">New</span> population <span class="hljs-keyword">of</span> USA <span class="hljs-keyword">is</span> <span class="hljs-number">32001206</span>
<span class="hljs-built_in">New</span> population <span class="hljs-keyword">of</span> USA <span class="hljs-keyword">is</span> <span class="hljs-number">32001176</span>
<span class="hljs-built_in">New</span> population <span class="hljs-keyword">of</span> USA <span class="hljs-keyword">is</span> <span class="hljs-number">32000957</span>
<span class="hljs-built_in">New</span> population <span class="hljs-keyword">of</span> USA <span class="hljs-keyword">is</span> <span class="hljs-number">32001005</span>
</code></pre><p>Hmm.. I gotta say, I'm kind of concerned here. If we are only tracking newborns , and not tracking the deceased... how come our population is actually lower in the last line than the first line?</p>
<p>Well, it's because we haven't implemented thread safety. Our various goroutines are accessing the same memory address without any respect for order. It's like those old people at the supermarket that pretend they don't see the line. </p>
<p>We need to implement some order here. </p>
<p>Enter Mutexes.</p>
<p>Mutex is short for Mutually Exclusive Lock. It's used so that when one thread (or goroutine in the case of Golang) is accessing a value inside a memory address, it can lock out the other threads so they have to wait in line. This guarantees that there will not be any of this random accessing and changing of values. Let's implement:</p>
<pre><code><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"sync"</span>
    <span class="hljs-string">"time"</span>
)

<span class="hljs-keyword">type</span> Country <span class="hljs-keyword">struct</span> {
    Name       <span class="hljs-keyword">string</span>
    Continent  <span class="hljs-keyword">string</span>
    Population <span class="hljs-keyword">int32</span>
    mu     sync.Mutex
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">updatePopulation</span><span class="hljs-params">(c *Country, newBorns <span class="hljs-keyword">int32</span>)</span></span> {
    c.mu.Lock()
    <span class="hljs-keyword">defer</span> c.mu.Unlock()
    c.Population += newBorns
    fmt.Printf(<span class="hljs-string">"New population of %v is %v\n"</span>, c.Name, c.Population)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    totalStates := <span class="hljs-number">50</span> <span class="hljs-comment">// total number of sources, (US states)</span>
    us := Country{<span class="hljs-string">"USA"</span>, <span class="hljs-string">"North America"</span>, <span class="hljs-number">32000000</span>, sync.Mutex{}}
    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; totalStates; i++ {
        <span class="hljs-keyword">go</span> updatePopulation(&amp;us, <span class="hljs-keyword">int32</span>(i))}
    time.Sleep(time.Second * <span class="hljs-number">5</span>)
}
</code></pre><p>The <code>sync.Mutex</code> is a struct that we use for implementing mutexes in Go. The default value is an unlocked  mutex, as you can see from the standard library code:</p>
<pre><code><span class="hljs-comment">// A Mutex is a mutual exclusion lock.</span>
<span class="hljs-comment">// The zero value for a Mutex is an unlocked mutex.</span>
<span class="hljs-comment">//</span>
<span class="hljs-comment">// A Mutex must not be copied after first use.</span>
<span class="hljs-keyword">type</span> Mutex <span class="hljs-keyword">struct</span> {
    state <span class="hljs-keyword">int32</span>
    sema  <span class="hljs-keyword">uint32</span>
}
</code></pre><p>  Now, let's run our app again and see what the result will be:</p>
<pre><code><span class="hljs-built_in">New</span> population <span class="hljs-keyword">of</span> USA <span class="hljs-keyword">is</span> <span class="hljs-number">32000979</span>
<span class="hljs-built_in">New</span> population <span class="hljs-keyword">of</span> USA <span class="hljs-keyword">is</span> <span class="hljs-number">32001023</span>
<span class="hljs-built_in">New</span> population <span class="hljs-keyword">of</span> USA <span class="hljs-keyword">is</span> <span class="hljs-number">32001072</span>
<span class="hljs-built_in">New</span> population <span class="hljs-keyword">of</span> USA <span class="hljs-keyword">is</span> <span class="hljs-number">32001108</span>
<span class="hljs-built_in">New</span> population <span class="hljs-keyword">of</span> USA <span class="hljs-keyword">is</span> <span class="hljs-number">32001146</span>
<span class="hljs-built_in">New</span> population <span class="hljs-keyword">of</span> USA <span class="hljs-keyword">is</span> <span class="hljs-number">32001185</span>
<span class="hljs-built_in">New</span> population <span class="hljs-keyword">of</span> USA <span class="hljs-keyword">is</span> <span class="hljs-number">32001225</span>
</code></pre><p>This looks good. The values are constantly incrementing, meaning that order is restored. Now, you might wonder why we use the <code>defer c.mu.Unlock()</code>  code immediately under the line of code where we establish the lock. The reason for this is because we need to avoid a <em>deadlock</em>. Deadlocks are vulnerabilities of mutexes that must be avoided at all cost. Imagine something happens between the locking of a memory address and it's unlocking that causes the goroutine to stop. It would mean that this lock is going to be implemented indefinitely and that all of the other goroutines will not be able to access it at all. This is why we use the <code>defer</code> keyword, because it will guarantee that no matter what happens in that function, it will unlock after exiting. </p>
<p>I'd also like to mention that beside the standard <code>sync.Mutex</code> that we used above, there also exists another mutex - <code>sync.RWMutex</code> . </p>
<p>That's right folks, the complexity is far from finished. Whoever told you that Golang is easy ( that would be me, just a few articles ago) really had no idea about the low-level concepts you need to master before using it responsibly. </p>
<p>The point is that each time a goroutine implements a lock, the other goroutines have to wait in line, thus slowing down the overall performance. But, what if these goroutines just want to read the value from that memory address. That's safe, right? Why would the goroutine that implemented the lock hog the memory address all to itself, if the others promise not to change anything, just read the value and go on with their business.</p>
<p>So if you change the <code>sync.Mutex</code> field in the Country struct to be <code>sync.RWMutex</code> , you now have the possibility of getting even more functionality:</p>
<p><strong>1. Lock(): only one go routine reads/writes at a time by acquiring the lock.</strong></p>
<p><strong>2. RLock(): multiple go routines can read(not write) at a time by acquiring the lock.</strong></p>
<p>I actually copy/pasted these two definitions from Stack Overflow (like any well mannered programmer would do) . Here is the original post:</p>
<p>https://stackoverflow.com/questions/53427824/what-is-the-difference-between-rlock-and-lock-in-golang</p>
<p>Finally, I want to address the fact that most of you who were coming from Python and JavaScript like me, were probably shocked to even learn that something like a Mutex even exists. The reason we never heard of this concept from our dear dynamically typed, interpreted languages is because in the case of Python (CPython to be specific) the GIL (Global Interpreter Lock) acts a a gigantic Mutex over everything, so using explicit locks wouldn't really change anything. Although, you can implement a Lock and Unlock by using the <code>threading</code> library, but even the documentation says:</p>
<p><em>CPython implementation detail: In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once (even though certain performance-oriented libraries might overcome this limitation). If you want your application to make better use of the computational resources of multi-core machines, you are advised to use multiprocessing or concurrent.futures.ProcessPoolExecutor. However, threading is still an appropriate model if you want to run multiple I/O-bound tasks simultaneously.</em></p>
<p>Basically they are saying - just use the library for IO (but I would suggest using asyncio), and if you really need OS threads, Python probably isn't that great of an option. </p>
<p>For JavaScript devs, the reason is even simpler - you never used mutexes, because JavaScript has only one thread. And, guess what, it does it's job pretty well with it. Once again, if you are doing compute heavy operations that are time sensitive, go with C++ or Rust. Luckily, most modern backend servers don't need compute heavy operations, they are totally IO based, and spend most of their idle time waiting for a db server to return some input.  Golang is beautiful because it has the ability to use both  OS threads and goroutines. </p>
<p>That's all for this article. If I missed anything please leave a comment. Thanks for reading!</p>
]]></content:encoded></item><item><title><![CDATA[When Should You Use Pointers in Go]]></title><description><![CDATA[The concept of pointers in programming languages is quite old. C and C++ are probably the best examples of languages that are widely popular that use pointers. Golang, being inspired by C in many ways, implements explicit pointers as well. I say expl...]]></description><link>https://golongwithgolang.com/when-should-you-use-pointers-in-go</link><guid isPermaLink="true">https://golongwithgolang.com/when-should-you-use-pointers-in-go</guid><category><![CDATA[Go Language]]></category><category><![CDATA[Computer Science]]></category><category><![CDATA[programming languages]]></category><category><![CDATA[data structures]]></category><dc:creator><![CDATA[Pavle Djuric]]></dc:creator><pubDate>Thu, 11 Nov 2021 14:57:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1636643336616/dBQHtvaKu.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The concept of pointers in programming languages is quite old. C and C++ are probably the best examples of languages that are widely popular that use pointers. Golang, being inspired by C in many ways, implements explicit pointers as well. I say explicit, because the most popular programming languages like Python and JavaScript implement pointers also, except they do them implicitly so you don't even know about this. </p>
<p>Ever hear of the term "pass by reference" ? It's used all the time in Python, JS and many more. Here's an example in Python to describe what I mean:</p>
<pre><code><span class="hljs-string">a</span> <span class="hljs-string">=</span> [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>]
<span class="hljs-string">b</span> <span class="hljs-string">=</span> <span class="hljs-string">a</span>
<span class="hljs-string">b.append(4)</span>
<span class="hljs-string">print(a)</span>
</code></pre><p>You'll see from this simple example that not only are the values of <code>a</code> and <code>b</code> the same, but a and b <em>are</em> the same. You can check this by printing the memory addresses of both:</p>
<pre><code>print(id(a))
print(id(b))
</code></pre><p>The reason they are the same is because when we say <code>b=a</code>, we're not saying assign <code>b</code> the value of <code>a</code>, rather assign <code>b</code> to be a pointer to <code>a</code>.</p>
<p>Languages like Python and JavaScript were created to abstract away many low level concepts so that developers had less on their mind, and could focus more on business logic. These languages were created in the 1990s when memory was scarce. Why is that important for pointers? Well, imagine you have a data structure like this:</p>
<pre><code>people = {<span class="hljs-number">1</span>: {<span class="hljs-string">'name'</span>: <span class="hljs-string">'John'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-string">'27'</span>, <span class="hljs-string">'sex'</span>: <span class="hljs-string">'Male'</span>},
          <span class="hljs-number">2</span>: {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Annie'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-string">'22'</span>, <span class="hljs-string">'sex'</span>: <span class="hljs-string">'Female'</span>},
          <span class="hljs-number">3</span>: {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Jane'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-string">'42'</span>, <span class="hljs-string">'sex'</span>: <span class="hljs-string">'Female'</span>},
          <span class="hljs-number">4</span>: {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Bob'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-string">'31'</span>, <span class="hljs-string">'sex'</span>: <span class="hljs-string">'Male'</span>},
          <span class="hljs-number">5</span>: {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Andy'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-string">'36'</span>, <span class="hljs-string">'sex'</span>: <span class="hljs-string">'Male'</span>},
          <span class="hljs-number">6</span>: {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Lisa'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-string">'32'</span>, <span class="hljs-string">'sex'</span>: <span class="hljs-string">'Female'</span>},
          <span class="hljs-number">7</span>: {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Jimmy'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-string">'26'</span>, <span class="hljs-string">'sex'</span>: <span class="hljs-string">'Male'</span>},
          <span class="hljs-number">8</span>: {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Gregory'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-string">'36'</span>, <span class="hljs-string">'sex'</span>: <span class="hljs-string">'Male'</span>}}
</code></pre><p>Let's see how much memory this object will take up when placed in the heap:</p>
<p><code>print(sys.getsizeof(people))</code></p>
<p>360 bytes. Not too big, but we could easily imagine this dictionary containing 800 keys instead of 8. Imagine copying the value of this variable whenever we wanted to do something with it. You would potentially run out of memory if memory was scarce and expensive, like in the previous decades.
 Wouldn't it be cheaper to just copy a reference to this variable.  It's like having 200 pounds of sugar (for whatever reason maybe you really like sugar, just stick with me) . Would you rather always carry that huge load of sugar around with you, or would you perhaps store it in some locker, write down the address of that locker, and then when you need some (or all) of that sugar you just go to that address.</p>
<p>That's the whole point of pointers (no pun intended). </p>
<p>Pointers are integers that store the value of the memory address. Being integers, they only take up 4 bytes on a 32 bit system, or 8 bytes on a 64 bit system. Which is way less than the 360 bytes (or potentially 36000 bytes) that our <code>people</code> variable value takes up.</p>
<p>However, passing around references can get complex and error prone sometimes, that is why it is good to have an option to pass by value as well. </p>
<p>Golang, unlike Python or JavaScript, is a <em>pass by value</em> language. If you want to pass by reference, you use explicit pointers.</p>
<p>Okay, so basically we should use pointers all the time, right?</p>
<p>No.</p>
<p>In fact, I'll quote Ben Darnell, who is the lead engineer of CockroachDB (built in Go) :</p>
<p>"Whenever in doubt, use a value instead of a pointer"</p>
<p>We're no longer in the 1990s , memory is cheap. If you don't need a pointer, you should stick to a value. However, in many cases, you will indeed need a pointer.</p>
<p>Here are some of the common situations where you will need to use a pointer instead of a value:</p>
<p><strong>1. Changing the state of an object:</strong></p>
<p>Let's say you have a struct like this</p>
<pre><code><span class="hljs-keyword">type</span> Person <span class="hljs-keyword">struct</span> {
    name     <span class="hljs-keyword">string</span>
    age      <span class="hljs-keyword">int</span>
    gender   <span class="hljs-keyword">string</span>

}
</code></pre><p>Now, you want a method that will enable you to change the name of a person.
Coming from Python, your gut instinct would tell you to write</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(p Person)</span> <span class="hljs-title">changeName</span><span class="hljs-params">(name <span class="hljs-keyword">string</span>)</span></span>{
    p.name = name
}
</code></pre><p>The problem is, Golang being Golang, you are passing by value, meaning you are not passing the real <code>p</code> but only a clone that copies it's values. Changing the state of the clone will not affect the original.</p>
<p>This is why you need a pointer here. </p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(p *Person)</span> <span class="hljs-title">changeName</span><span class="hljs-params">(name <span class="hljs-keyword">string</span>)</span></span>{
    p.name = name
}
</code></pre><p><strong>2. Enabling variables to have nil values</strong></p>
<p>This is a gotcha that leads a lot of Go beginners to create bugs. A variable that is defined, but not assigned a value, does not evaluate to <code>nil</code> but rather to it's default value. For booleans this is <code>false</code>, for integers it is <code>0</code>, for strings it is an empty string. But, what if you need it to be <code>nil</code>. Say you have a REST API endpoint that allows end users to create accounts in your application by using the POST /accounts endpoint. They pass their info in the body of this request and your backend Go server then converts this JSON body into a <code>User</code> struct, does some validations, and then stores this data in the database. Suppose you write your struct like this:</p>
<pre><code><span class="hljs-keyword">type</span> User <span class="hljs-keyword">struct</span> {
    username   <span class="hljs-keyword">string</span>
    email      <span class="hljs-keyword">string</span>
    profession <span class="hljs-keyword">string</span>
    country    <span class="hljs-keyword">string</span>
}
</code></pre><p>Now, let's say that some user sends their POST request to your server, but leaves the <code>profession</code> parameter out of the body because it is a non-required parameter, and the user wishes not to specify their profession. The way this struct is defined, the profession would not evaluate to <code>nil`` , but to</code>''``` . Is this some kind of new profession? Or is this intended to be empty? Did the user mistakenly pass an empty string? Here, it would be more appropriate to use a pointer to a string, instead of just a string. You could also imagine situation where an integer evaluates to 0, when the value shouldn't even exist, because it wasn't specified. Imagine a football match struct:</p>
<pre><code><span class="hljs-keyword">type</span> Match <span class="hljs-keyword">struct</span> {
    homeTeam        <span class="hljs-keyword">string</span>
    awayTeam         <span class="hljs-keyword">string</span>
    HomeTeamGoals <span class="hljs-keyword">int</span>
    AwayTeamGoals    <span class="hljs-keyword">int</span>
}
</code></pre><p>What if the match hasn't started yet. Wouldn't it be more appropriate if the HomeTeamGoals and AwayTeamGoals were nil instead of evaluating to 0. </p>
<p>Your application logic would be able to assert if a value is nil, then the match hasn't started. So better to define the struct like this:</p>
<pre><code><span class="hljs-keyword">type</span> Match <span class="hljs-keyword">struct</span> {
    homeTeam   <span class="hljs-keyword">string</span>
    awayTeam      <span class="hljs-keyword">string</span>
    HomeTeamGoals *<span class="hljs-keyword">int</span>
    AwayTeamGoals    *<span class="hljs-keyword">int</span>
}
</code></pre><p>Make it a rule that if you need a variable to be able to evaluate to nil, you need a pointer.</p>
<p><strong>3.  Copying struct that have very large values:</strong></p>
<p>Although memory is not that big of an issue today, you might still want to use a reference if the value of the object is ridiculously large, and there is really no need to pass it around all the time. This will probably improve the performance and memory usage of your application (although probably not significantly) . There is a trade off, because now the garbage collector has more work to do, but in cases of very large and complex structs, I think using pointers makes more sense.</p>
<p>As you can see, using pointers is sometimes over-engineering, and although it makes the code seemingly look sophisticated it's actually doing damage. However, sometimes you have no other option.</p>
<p>Thanks for reading, and if I missed anything important, please leave a comment :)</p>
]]></content:encoded></item><item><title><![CDATA[How to connect your Go web app to a Redis server]]></title><description><![CDATA[If there's one technology that is on par with Golang on the "coolness" scale, it is definitely Redis. Backend developers love it.  For four years in a row it is officially the most loved db, according to  Stack Overflow’s Annual Developer Survey  .
A...]]></description><link>https://golongwithgolang.com/how-to-connect-your-go-web-app-to-a-redis-server</link><guid isPermaLink="true">https://golongwithgolang.com/how-to-connect-your-go-web-app-to-a-redis-server</guid><category><![CDATA[Redis]]></category><category><![CDATA[caching]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Databases]]></category><dc:creator><![CDATA[Pavle Djuric]]></dc:creator><pubDate>Tue, 19 Oct 2021 19:14:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1634670802574/jSt5erG2d.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If there's one technology that is on par with Golang on the "coolness" scale, it is definitely Redis. Backend developers love it.  For four years in a row it is officially the most loved db, according to <a target="_blank" href="https://redis.com/blog/redis-is-the-most-loved-database-for-the-4th-year-in-a-row/"> Stack Overflow’s Annual Developer Survey </a> .</p>
<p>Although it is officially a NoSQL database, you'll usually use it as a cache, or maybe a pub-sub system. Some developers are advocating using it as a primary database, but I think for now that's a bit too extreme.</p>
<p>In this article, we'll look at some code that basically implements a couple of simple API endpoints, that use Redis to access/store the data.</p>
<p>I'll also be using commands like <code>go mod init</code> and <code>go get</code> to initiate a go module and get the third party package I will use to connect to my Redis instance. </p>
<p>By the way, I'll be running Redis in Docker, so if you have Docker installed on your local machine you should run <code>docker run -d -p 6379:6379 redis</code> to get it up and running. If not, either install Redis locally, or install Docker locally and then run the command above.</p>
<p>So, let's initate a go module and fetch the go Redis driver. I'll do this by typing the following commands in my terminal, in the directory where I'm going to write my code:</p>
<pre><code><span class="hljs-keyword">go</span> mod init github.com/pavledjuric/go_redis_webapp
<span class="hljs-keyword">go</span> get github.com/<span class="hljs-keyword">go</span>-redis/redis/v8
</code></pre><p>By the way, just because I name my module with the github.com prefix, doesn't mean it's actually going to be on GH, but if I were to push this code to a git repo, then I would push it to that one.</p>
<p>Now I have a module and the redis driver, so let me create a simple web server:</p>
<pre><code><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"log"</span>
    <span class="hljs-string">"net/http"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

    port := <span class="hljs-string">":8080"</span>
    http.HandleFunc(<span class="hljs-string">"/users"</span>, <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
        w.Write([]<span class="hljs-keyword">byte</span>(<span class="hljs-string">"Hellooo users!!"</span>))
    })
    log.Fatal(http.ListenAndServe(port, <span class="hljs-literal">nil</span>))
}
</code></pre><p>Boring! A simple http server with a single endpoint that doesn't do anything smart. So, let's make that handler take some data from Redis, and be able to write some data to Redis if it's a POST request. I'll also store my handlers in a separate package called <code>handlers</code> just to make it seem more like a real app.</p>
<p>Just so we're on the same page, and there's no issue with imports, your <code>main.go</code> file should go in a directory called <code>cmd</code> . That is go jargon for command, and that's where the executable usually goes. Your <code>handlers</code> directory and all of it's files should go in a directory called <code>pkg</code>. You guessed it , that's short for packages. This is how your project directory tree should look like:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634668371428/KNL7RkW1_.png" alt="image.png" /></p>
<p>Now let's write the code for our <code>handlers.go</code> file:</p>
<pre><code><span class="hljs-keyword">package</span> handlers

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"context"</span>
    <span class="hljs-string">"io/ioutil"</span>
    <span class="hljs-string">"net/http"</span>

    <span class="hljs-string">"github.com/go-redis/redis/v8"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">UsersHandler</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
    <span class="hljs-keyword">switch</span> r.Method {
    <span class="hljs-keyword">case</span> <span class="hljs-string">"GET"</span>:
        <span class="hljs-keyword">var</span> ctx = context.Background()

        red := redis.NewClient(&amp;redis.Options{
            Addr:     <span class="hljs-string">"localhost:6379"</span>,
            Password: <span class="hljs-string">""</span>,
            DB:       <span class="hljs-number">0</span>,
        })
        res, err := red.Get(ctx, <span class="hljs-string">"user"</span>).Result()
        <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
            w.Write([]<span class="hljs-keyword">byte</span>(<span class="hljs-string">"Error!"</span>))

        }
        w.Write([]<span class="hljs-keyword">byte</span>(res))
    <span class="hljs-keyword">case</span> <span class="hljs-string">"POST"</span>:
        body, err := ioutil.ReadAll(r.Body)
        <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
            w.Write([]<span class="hljs-keyword">byte</span>(<span class="hljs-string">"Error!"</span>))
        }
        <span class="hljs-keyword">defer</span> r.Body.Close()
        <span class="hljs-keyword">var</span> ctx = context.Background()

        red := redis.NewClient(&amp;redis.Options{
            Addr:     <span class="hljs-string">"localhost:6379"</span>,
            Password: <span class="hljs-string">""</span>,
            DB:       <span class="hljs-number">0</span>,
        })
        _, err = red.SetNX(<span class="hljs-string">"user"</span>, body, <span class="hljs-number">60</span>*time.Second).Result()
        <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
            w.Write([]<span class="hljs-keyword">byte</span>(<span class="hljs-string">"Error!"</span>))

        }
        w.Write([]<span class="hljs-keyword">byte</span>(body))

    }

}
</code></pre><p>It may look a bit confusing but it's actually pretty self explanatory. We're using a switch statement that will execute code depending on the HTTP method of the request we're handling (GET or POST) . </p>
<p>If it's GET, we'll create a context and a connection to our Redis server. Next , we'll try to get the data that is stored in the <em>user </em> key in the our Redis db. If we can't find that key, that will return an error, and our server will let us know it's an error. </p>
<p>If the request method is POST, we'll read from the request body and store that data in the <em>user</em> key in Redis with a 60 second time to live. This means that after 60 seconds the data will be deleted from Redis, thus mimicking how a real caching system would work. Of course, in a real application, we would store the data permanently in an SQL or NoSQL database apart from storing it temporarily in the cache. </p>
<p>There's one thing I'd still like to do here. This code doesn't seem too DRY (don't repeat yourself) , since I'm instantiating the <code>redis.NewClient</code> twice with all the connection parameters unnecessarily. Let's extract that to a function, and create another package to store it in. I'll call the package <code>redisconn</code>, so now my project tree looks like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634752590329/5NU2TqJrW.png" alt="image.png" /></p>
<p>The code for the redis connection will go in the <code>redisconn</code> package. Basically, it's just a wrapper to the redis driver we downloaded, but perhaps we wan't to add some custom logic after, so it's a good idea to have it in a separate package:</p>
<pre><code><span class="hljs-selector-tag">package</span> <span class="hljs-selector-tag">redisconn</span>

<span class="hljs-selector-tag">import</span> (
    <span class="hljs-string">"github.com/go-redis/redis"</span>
)

<span class="hljs-selector-tag">func</span> <span class="hljs-selector-tag">GetRedisConnection</span>() *<span class="hljs-selector-tag">redis</span><span class="hljs-selector-class">.Client</span> {

    <span class="hljs-selector-tag">return</span> <span class="hljs-selector-tag">redis</span><span class="hljs-selector-class">.NewClient</span>(&amp;redis.Options{
        <span class="hljs-attribute">Addr</span>:     <span class="hljs-string">"localhost:6379"</span>,
        <span class="hljs-attribute">Password</span>: <span class="hljs-string">""</span>,
        <span class="hljs-attribute">DB</span>:       <span class="hljs-number">0</span>,
    })
}
</code></pre><p>Now back to the handlers package, let's import <code>redisconn</code> and update the code. I also wan't to add an http status code of <code>404</code> if the data is not found, and <code>500</code> if for some reason the server crashes while reading data from the POST request (I forgot to do that initially, and I'm too lazy to update it honestly) :</p>
<pre><code><span class="hljs-keyword">package</span> handlers

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"io/ioutil"</span>
    <span class="hljs-string">"net/http"</span>

    <span class="hljs-string">"github.com/pavledjuric/go_redis_webapp/pkg/redisconn"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">UsersHandler</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
    <span class="hljs-keyword">switch</span> r.Method {
    <span class="hljs-keyword">case</span> <span class="hljs-string">"GET"</span>:
        red := redisconn.GetRedisConnection()
        res, err := red.Get(<span class="hljs-string">"user"</span>).Result()
        <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
            http.Error(w, <span class="hljs-string">"Error!"</span>, <span class="hljs-number">404</span>)
            <span class="hljs-keyword">return</span>

        }
        w.Write([]<span class="hljs-keyword">byte</span>(res))
    <span class="hljs-keyword">case</span> <span class="hljs-string">"POST"</span>:
        body, err := ioutil.ReadAll(r.Body)
        <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
            http.Error(w, <span class="hljs-string">"Internal server error"</span>, <span class="hljs-number">500</span>)
            <span class="hljs-keyword">return</span>
        }
        <span class="hljs-keyword">defer</span> r.Body.Close()

        red := redisconn.GetRedisConnection()
        _, err = red.SetNX(<span class="hljs-string">"user"</span>, body, <span class="hljs-number">60</span>*time.Second).Result()
        <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
            http.Error(w, <span class="hljs-string">"Internal server error"</span>, <span class="hljs-number">500</span>)
            <span class="hljs-keyword">return</span>

        }
        w.Write([]<span class="hljs-keyword">byte</span>(body))

    }

}
</code></pre><p>Ok, that definitely looks a bit cleaner now.</p>
<p>So let's try it out:</p>
<p>I first try the GET request, knowing that my Redis db is empty:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634669133840/FqjKbqmFA.png" alt="image.png" /></p>
<p>Looking good. Now I'll add my user to Redis by sending a POST request. I'll use Postman , but you can use curl or whatever you preffer:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634669252308/vK1y1IOml.png" alt="image.png" /></p>
<p>Ok, it seems to have worked, so let's call the GET /users endpoint again:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634669294412/dqegyq4IY.png" alt="image.png" /></p>
<p>Beautiful! </p>
<p>However, I'm a bit paranoid by nature, so I wan't to make sure this data is actually coming from Redis, and not some alien hackers from another planet. Let me go inside the docker container that is running Redis and check. I enter the container by running the following command</p>
<pre><code>  docker <span class="hljs-keyword">exec</span> -it a1b redis-cli
</code></pre><p>This <em>a1b</em> is the first 3 characters of my container ID , yours will most definitely be different . You can check it by running <code>docker ps</code> .</p>
<p>Ok, so I'm in my Redis container, inside the redis cli tool.  I run <code>keys *</code> to see that user is indeed there. I run <code>get user</code> to find that the data is definitely coming from Redis:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634669572678/BjWYZF7B5.png" alt="image.png" /></p>
<p>I'm truly relieved it was not the aliens.</p>
<p>Remeber how we added a 60 second time to live for the data inside Redis, so let's check how much time it has left by using the <code>ttl</code> command:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634754650026/Aa6t_pROI.png" alt="image.png" /></p>
<p>Now let's wait out those 52 seconds and check again:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634754693805/-Famb_3Di.png" alt="image.png" /></p>
<p>Looking good. What about our API server, does he agree? </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1634754759460/A9ecXe97p.png" alt="image.png" /></p>
<p>He does indeed! Seems like everything is working as intended.</p>
<p>In conclusion I would say that connecting Redis to your Go API server is pretty simple as you can see, and it will boost your response times significantly. Typically, you would use a SQL database as a primary db, and Redis would be in front of it. When a user would request data from your API server, the server would first check Redis for the data. If Redis has it, it will return it in a blazing fast manner. If it this data is not in Redis, the server would then retrieve the data from the SQL server (MySQL, Postgres or whatever you’re using), and on it's way back store that data in Redis, with a specified time to live (because your data is probably dynamic and changes often , so you do not want your cache to store it indefinitely) . This is known as the <em>cache-aside </em>pattern. There are other caching patterns like <em>write-through</em>, but I usually use cache-aside and I recommend it for most cases.</p>
<p>That's all for this one folks. Thanks for reading.</p>
]]></content:encoded></item><item><title><![CDATA[The glorious net/http Go module]]></title><description><![CDATA[If you're in to web development, you've probably heard someone talking about how Golang is the language for modern backend development. It was built by a team of people who really know their stuff, at a company that reeaally knows it's stuff. 
Beside...]]></description><link>https://golongwithgolang.com/the-glorious-nethttp-go-module-1</link><guid isPermaLink="true">https://golongwithgolang.com/the-glorious-nethttp-go-module-1</guid><category><![CDATA[Go Language]]></category><category><![CDATA[http]]></category><category><![CDATA[json]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[programming languages]]></category><dc:creator><![CDATA[Pavle Djuric]]></dc:creator><pubDate>Wed, 13 Oct 2021 19:42:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1634154105731/dFm9CSCoS.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you're in to web development, you've probably heard someone talking about how Golang is the language for modern backend development. It was built by a team of people who really know their stuff, at a company that reeaally knows it's stuff. </p>
<p>Besides the nice and simple syntax, one of it's main advantages is the standard library that is fully equipped with modules that are production ready, and extremely well designed  ( there's also a number of great third party modules, but more about some of those in another article) .</p>
<p>One of the finest modules from the Go standard library is definitely <code>net/http</code> , which makes sense, because you really can't do web without the http protocol.</p>
<p>It has a production ready web server, and an extremely easy to use http client for sending requests. Let's see how easy it is to run a web server in Go:</p>
<pre><code><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"net/http"</span>
)

<span class="hljs-keyword">const</span> portNumber = <span class="hljs-string">":8080"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">HomePageHandler</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
    w.Write([]<span class="hljs-keyword">byte</span>(<span class="hljs-string">"We're live !!!"</span>))
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

    http.HandleFunc(<span class="hljs-string">"/"</span>, HomePageHandler)
    fmt.Printf(<span class="hljs-string">"Starting application on port %v\n"</span>, portNumber)
    http.ListenAndServe(portNumber, <span class="hljs-literal">nil</span>)
}
</code></pre><p>Pretty self explanatory, right? I've even added a few more lines of code than necessary, just to make things more obvious. The <code>HandleFunc</code> method attaches a route to a handler, and each handler function must accept an http request ( a pointer to it actually) , and a response writer which is in charge of sending the response back via the net to the client. </p>
<p>Another way of writing the handler would have been :</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">HomePageHandler</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
    fmt.Fprintf(w, <span class="hljs-string">"We're live!!!"</span>)
}
</code></pre><p>It really depends on style. <code>Fprintf</code> takes any type that implements the <code>io.Writer</code> interface ( the <code>http.Responsewriter</code> is a marvelous example of this, but so is <code>os.Stdout</code>) as a first argument, and a string as a second argument. The string is what we're displaying, and the io.Writer is where we're displaying it. </p>
<p>If we're going to call <code>w.Write</code> , we know that as an implementation of the <code>Write</code> function of the <code>io.Writer</code> interface, we need to give it a slice of bytes, not a string. Luckily converting a string to a slice of bytes is a slice of cake.</p>
<p>  Let's take a look at this *http.Request thingamajig:</p>
<pre><code><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"net/http"</span>
)

<span class="hljs-keyword">const</span> portNumber = <span class="hljs-string">":8080"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">HomePageHandler</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {
    fmt.Fprintf(w, <span class="hljs-string">"Hello %v, you are at %v. You have sent some query params too: %v.The method you used is %v"</span>, r.UserAgent(), r.URL.Path, r.URL.Query(), r.Method)

}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

    http.HandleFunc(<span class="hljs-string">"/hello"</span>, HomePageHandler)
    fmt.Printf(<span class="hljs-string">"Starting application on port %v\n"</span>, portNumber)
    http.ListenAndServe(portNumber, <span class="hljs-literal">nil</span>)
}
</code></pre><p>I've updated the code so that it is clear that the request struct has everything we need for handling an http request, just like we would with any cool web framework like Flask or Spring Boot. Except, this is not a framework, it's the standard library http module. Ok, I will admit that using a framework like <code>Gin Gonic</code> or <code>Gorilla</code> will speed you up, and keep you from writing a lot of boilerplate code, but for a stadard library http module, this is pretty practical.</p>
<p>Now, what about sending http requests to a remote server. Has anyone written a cool http client for Go, something in the line of the massively successful <em>requests</em> library in Python?</p>
<p>Actually, the original Go creators decided not to give anyone a chance to do that, because the net/http module contains such a simple http client , that there really wasn't any need for a third party library.</p>
<p>Here's a call to github's API:</p>
<pre><code><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"io/ioutil"</span>
    <span class="hljs-string">"log"</span>
    <span class="hljs-string">"net/http"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

    req, err := http.Get(<span class="hljs-string">"https://api.github.com/users"</span>)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        log.Fatal(err)
    }
    <span class="hljs-keyword">defer</span> req.Body.Close()
    data, err := ioutil.ReadAll(req.Body)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        log.Fatal(err)
    }
    fmt.Println(<span class="hljs-keyword">string</span>(data))

}
</code></pre><p>Probably the most complicated code here is all of this error checking, but when considering try/catch blocks in other languages, it's not even that bad.
I'm calling <code>defer req.Body.Close()</code> here because it's good practice to close a request body, same as you would close a file once you've finished reading from it.</p>
<p>Since the request body is an implementation of the <code>io.ReadCloser</code> interface (what's with all these io module interfaces, right? ) , we can't just print that , we need to call <code>ioutil.Readall</code> which will take the request body and return a byte slice. As we know, turning a byte slice into a string (and vice versa) is not difficult.  </p>
<p>Finally, since a large part of backend development today is concerned with REST APIs, I guess it wouldn't be bad to implement a basic GET endpoint that returns some JSON so that the output we get at least remotely resembles something you would see in real life:</p>
<pre><code><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"encoding/json"</span>
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"log"</span>
    <span class="hljs-string">"net/http"</span>
)

<span class="hljs-keyword">const</span> portNumber = <span class="hljs-string">":8080"</span>

<span class="hljs-keyword">type</span> User <span class="hljs-keyword">struct</span> {
    Name   <span class="hljs-keyword">string</span> <span class="hljs-string">`json:"username"`</span>
    Age    <span class="hljs-keyword">int</span>    <span class="hljs-string">`json:"age"`</span>
    Gender <span class="hljs-keyword">string</span> <span class="hljs-string">`json:"gender"`</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">UsersHandler</span><span class="hljs-params">(w http.ResponseWriter, r *http.Request)</span></span> {

    users := []User{
        {
            Name:   <span class="hljs-string">"Chris"</span>,
            Age:    <span class="hljs-number">22</span>,
            Gender: <span class="hljs-string">"Male"</span>,
        },
        {
            Name:   <span class="hljs-string">"Annie"</span>,
            Age:    <span class="hljs-number">23</span>,
            Gender: <span class="hljs-string">"Female"</span>,
        },
        {
            Name:   <span class="hljs-string">"Jane"</span>,
            Age:    <span class="hljs-number">25</span>,
            Gender: <span class="hljs-string">"Female"</span>,
        },
    }

    usersJson, err := json.Marshal(users)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        log.Fatal(err)
    }
    w.Write(usersJson)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

    http.HandleFunc(<span class="hljs-string">"/users"</span>, UsersHandler)
    fmt.Printf(<span class="hljs-string">"Starting application on port %v\n"</span>, portNumber)
    http.ListenAndServe(portNumber, <span class="hljs-literal">nil</span>)
}
</code></pre><p>Alright mister, you've got a lot of explaining to do! Wtf are these weird back ticks next to your struct fields? and why are all the fields in the struct capitalized? </p>
<p>Good questions!</p>
<p>The weird back ticks are an awesome feature of Golang. In this case we are using them to describe what we want the keys of our fields to be called when we serialize them to JSON. So Name becomes username. Now, we could have left it as a POGS ( Plain Old Go Struct ? ) , but then the JSON field would be name with a capitalized N, which really isn't the convention when displaying data in JSON format. But, then I guess we could have lowercased the Name field , and that would solve it right? ( forget for a moment that I actually changed name to username, it would have worked however you named it)</p>
<p>No, it wouldn't . If you're coming from Java, you know all about encapsulation. <code>private String name</code> you would proudly type, and the whole world would know that name is not to be touched unless it has a setter. Well, Go doesn't like verbosity. In fact, Go developers had the audacity to call Java a stuttery language. 
<code>Person person = new Person()</code> .. well, it does sound a bit like stuttering. 
Go does respect encapsulation though. Kind of, not as explicitly as Java, but it definitely doesn't rely on the whole <em>we're all grownups</em> rambling of Python developers. Because Go developers know that grownups are quite irresponsible, so it's better not to rely on them. 
How does Go take care of encapsulation? Easy, if it's capitalized it's not encapsulated ( I almost spelled encapitalized) . So <em>Name</em> as a field is available to the public, while <em>name</em> would not be. Besides exporting or restricting the use of functions and struct fields to different packages, it is extremely useful for filtering what fields to send to the client, and which not to. Besides for JSON, the back ticks are used for many other purposes, such as in ORMs like <code>gorm</code> , but that is definitely going to be an article of it's own.</p>
<p>Hope you enjoyed this article, thanks for reading! </p>
]]></content:encoded></item><item><title><![CDATA[Interfaces in Golang]]></title><description><![CDATA[If you're coming from Java, you definitely know about interfaces. If you're coming from Python, you're probably scratching your head. But, no matter which language you're coming from, you'll be surprised about how Go implements interfaces.
An interfa...]]></description><link>https://golongwithgolang.com/interfaces-in-golang</link><guid isPermaLink="true">https://golongwithgolang.com/interfaces-in-golang</guid><category><![CDATA[Go Language]]></category><category><![CDATA[programming languages]]></category><category><![CDATA[data structures]]></category><dc:creator><![CDATA[Pavle Djuric]]></dc:creator><pubDate>Thu, 07 Oct 2021 18:11:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1633630231390/j0ak8X6wxq.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you're coming from Java, you definitely know about interfaces. If you're coming from Python, you're probably scratching your head. But, no matter which language you're coming from, you'll be surprised about how Go implements interfaces.</p>
<p>An interface is a type in Go. But, unlike the struct type, the interface type is not concerned with state, but with behavior. </p>
<p>For example, a Dog struct would look like this:</p>
<pre><code><span class="hljs-keyword">type</span> Dog <span class="hljs-keyword">struct</span> {
    name     <span class="hljs-keyword">string</span>
    age       <span class="hljs-keyword">int</span>
    gender  <span class="hljs-keyword">string</span>
    isHungry <span class="hljs-keyword">bool</span>
}
</code></pre><p>A Dog interface on the other hand would look like this:</p>
<pre><code><span class="hljs-keyword">type</span> Dog <span class="hljs-keyword">interface</span> {
    barks()
    eats()
}
</code></pre><p>The struct shows us some attributes of a dog, but the interface describes what this dog is supposed to do.</p>
<p>Now, let's say we're writing an application about .. well... dogs! We'll have a lot of different breeds. We know that Go does not support inheritance like OOP languages do , so instead of naming the struct Dog, let's name it Labrador, and as our app grows, we'll probably add more breeds.</p>
<pre><code><span class="hljs-keyword">type</span> Labrador <span class="hljs-keyword">struct</span> {
    name     <span class="hljs-keyword">string</span>
    age    <span class="hljs-keyword">int</span>
    gender <span class="hljs-keyword">string</span>
    isHungry <span class="hljs-keyword">bool</span>
}
</code></pre><p>For the purpose of our app, we'll want to split these different dogs into two groups - big dogs and small dogs ( suppose we want to know how much food each group needs). We need a function that adds a dog (no matter the breed) , to a group:</p>
<pre><code><span class="hljs-function">func <span class="hljs-title">addToGroup</span>(<span class="hljs-params">d Dog, <span class="hljs-keyword">group</span> []Dog</span>) []Dog</span> {
    <span class="hljs-keyword">group</span> = append(<span class="hljs-keyword">group</span>, d)
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">group</span>
}
</code></pre><p>This function is basically just a wrapper to the built-in append function, but for the sake of simplicity let's assume it's some super complex algorithm. </p>
<p>Notice that the <code>addToGroup</code> function only accepts the <code>Dog</code> interface, and a slice of Dogs. Nowhere is the Labrador type mentioned. But, what if we want to add a Labrador named Max to a group called Big dogs? 
 How will the Go compiler know that Labs are dogs?</p>
<p>Easy, Golang asynchronously googles " are labs dogs? " , and then based on that answer it knows. On the odd occasion that Google is down, it goes to Wikipedia.
 Just make sure you have an internet connection or it will not know.</p>
<p>Ok, probably no one laughed. </p>
<p>In all seriousness though, the Go compiler will know that the <code>Labrador</code> type implements the <code>Dog</code> interface (and thus gains access to all functions that accept a Dog interface) only if the Labrador type implements the methods described in the Dog interface.</p>
<p>In Java, it's a bit more explicit. You would type <code>class Labrador implements Dog</code>
and that would already indicate what you are doing. You would have to implement the methods also, but in Golang you only implement the methods, and implicitly your Lab becomes a Dog.</p>
<p>So let's implement the <code>barks()</code> and <code>eats()</code> methods so that the Go compiler will know what a Labrador is:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(l Labrador)</span> <span class="hljs-title">barks</span><span class="hljs-params">()</span></span> {
    fmt.Println(l.name + <span class="hljs-string">" says woof"</span>)
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(l Labrador)</span> <span class="hljs-title">eats</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">if</span> l.isHungry {
        fmt.Println(l.name + <span class="hljs-string">" is eating. Since he is a labrador, give him xxx brand of food."</span>)
    } <span class="hljs-keyword">else</span> {
        fmt.Println(l.name + <span class="hljs-string">" already ate. Come back later."</span>)
    }
}
</code></pre><p>Not really intelligent business logic, I admit, but as you know tutorials tend to keep it as simple as possible.</p>
<p>Now that the <code>Labrador</code> struct implements both methods specified in the <code>Dog</code> interface, it has access to all functions that accept type <code>Dog</code> as an argument.</p>
<p>Let's see some output in our terminal by adding all of this to our main function:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

    bigDogs := []<span class="hljs-type">Dog</span>{}
    <span class="hljs-built_in">max</span> := <span class="hljs-type">Labrador</span>{
        name:     <span class="hljs-string">"Max"</span>,
        age:      <span class="hljs-number">5</span>,
        gender:   <span class="hljs-string">"Male"</span>,
        isHungry: <span class="hljs-literal">true</span>,
    }

    <span class="hljs-built_in">max</span>.barks()
    <span class="hljs-built_in">max</span>.eats()
    fmt.<span class="hljs-type">Println</span>(<span class="hljs-string">"Our group of big dogs:"</span>, bigDogs)
    bigDogs = addToGroup(<span class="hljs-built_in">max</span>, bigDogs)
    fmt.<span class="hljs-type">Println</span>(<span class="hljs-string">"Our group of big dogs now:"</span>, bigDogs)
}
</code></pre><p>We first created a slice of Dogs called <code>bigDogs</code> where we will store all of our big dogs . Then we create a Labrador called Max. We call the <code>barks()</code> and <code>eats()</code> 
methods just to see that everything works (and also to feed poor Max, since his isHungry attribute is always set to true) . </p>
<p>It works, so let's add Max to our group of big dogs. Had he been a Chihuahua, he probably wouldn't fit in.</p>
<p>As we see , the <code>addToGroup</code> function gladly accepts Max the Lab, since it is clear to the Go compiler that Max is a Lab , and a Lab is a Dog.</p>
<p>But, this is just a toy example. Where does all this actually get used in production code?</p>
<p>Literally everywhere.</p>
<p>For example, the <code>io.Reader</code> and <code>io.Writer</code> interfaces are used all the time.
Whenever some type is used for reading some data (wherever it may come from), odds are it is implementing the <code>io.Reader</code> interface. If it is writing somewhere (to standard out, to a file etc.) ,  it is most likely implementing the <code>io.Writer</code> interface.</p>
<p>They are actually pretty simple to implement. Here is the <code>io.Reader</code> interface:</p>
<pre><code><span class="hljs-keyword">type</span> Writer <span class="hljs-keyword">interface</span> {
    Write(p []<span class="hljs-keyword">byte</span>) (n <span class="hljs-keyword">int</span>, err error)
}
</code></pre><p>That's it. Any type that wants access to the functions that accept <code>io.Reader</code> as an argument (and there are quite a few), just needs to implement the <code>Write</code> method. Now, this doesn't mean that this implementation will necessarily be good. Interfaces work in a <strong>garbage in , garbage out</strong> manner, so if you implement the Write method poorly, you won't get the behavior you're expecting.</p>
<p> Another thing to consider is that in order to implement an interface, the methods must have the exact same signature as described in the interface. If your Write method does not accept a byte slice and return an integer and an error, you didn't do it right. </p>
<p>It's also worth mentioning that you can embed interfaces also.  Get a load of this:</p>
<pre><code><span class="hljs-keyword">type</span> ReadWriter <span class="hljs-keyword">interface</span> {
    Reader
    Writer
}
</code></pre><p>The <code>ReadWriter</code> interface implements both the <code>Reader</code> and the <code>Writer</code> interfaces, meaning any type that wants access to functions that take <code>ReadWriter</code> as an argument must implement all methods from the <code>Reader</code> and from the <code>Writer</code> interfaces (which are a total of only two methods, luckily) .</p>
<p>Finally, I want to talk about the empty interface. Let's say you wan't to use a hashmap, but you want to use various data types for the map's values. Since the hashmap is statically typed, you need to give it some type, so that would probably disable you from using more than one type. This is where the empty interface comes in. </p>
<p>An empty interface doesn't implement any behavior, so basically any data type satisfies that, just by merely existing. </p>
<p>It's kind of a hack tbh, but it can come handy sometimes, and it helps developers who are migrating from loosely typed languages like Python and JavaScript. </p>
<p>You would define your map like this:</p>
<pre><code>maxMap := <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">interface</span>{}{}
</code></pre><p>The two curly braces at the end look a bit strange , right? The first one belongs to the empty interface, and the second instantiates the map.</p>
<p>For better readability, you can make use of the <code>make</code> function:</p>
<pre><code>maxMap := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">interface</span>{})
</code></pre><p>For even better readability , you can create your own type, which will basically just implement the empty interface:</p>
<pre><code><span class="hljs-keyword">type</span> Any <span class="hljs-keyword">interface</span>{}

maxMap := <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]Any{}
</code></pre><p>And now we can assign different data types as the values of our map, without the Go compiler being in a nasty mood:</p>
<pre><code>maxMap["name"] = "some name"
maxMap["age"] = <span class="hljs-number">5</span>
maxMap["gender"] = "Male"
maxMap["isHungry"] = <span class="hljs-keyword">true</span>

fmt.Println(maxMap)
</code></pre><p>I personally thought all of this interface logic was really confusing and unnecessarily complex at first (especially coming from Java, where interfaces are more explicit) , but it actually makes sense after time. </p>
<p>The good thing is that you probably won't be writing a lot of your own interfaces, at least not for most day to day features. </p>
<p>But, it is something you definitely need to know, as it will be appearing all the time in code that you use from modules in the standard library. Just look at the <a target="_blank" href="https://pkg.go.dev/net/http">http module</a> . It's flooded with interfaces. Understanding them will help you in debugging a lot.</p>
<p>That's all folks, thanks for reading! </p>
]]></content:encoded></item><item><title><![CDATA[A short intro to goroutines and channels]]></title><description><![CDATA[Concurrency and parallelism. Quite a complex topic. Various programming languages tackle this issue in different ways. Some are really complicated, some a bit less. But, I would dare to say that Go really does well in this area. The reason why it han...]]></description><link>https://golongwithgolang.com/a-short-intro-to-goroutines-and-channels</link><guid isPermaLink="true">https://golongwithgolang.com/a-short-intro-to-goroutines-and-channels</guid><category><![CDATA[Go Language]]></category><category><![CDATA[programming languages]]></category><category><![CDATA[asynchronous]]></category><category><![CDATA[http]]></category><dc:creator><![CDATA[Pavle Djuric]]></dc:creator><pubDate>Thu, 30 Sep 2021 18:34:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1633026814785/DqBNgqa5U.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Concurrency and parallelism. Quite a complex topic. Various programming languages tackle this issue in different ways. Some are really complicated, some a bit less. But, I would dare to say that Go really does well in this area. The reason why it handles concurrency and parallelism so well, is because it was built with in the 21st century, when multi-core processors are an industry standard, and speed of execution is of the essence.</p>
<p><strong>What is a goroutine?</strong></p>
<p>A Goroutine is essentially a very lightweight substitute for a thread.  If you are coming from Java, you will probably know that a single Java thread allocates 1MB of memory by default. On the other hand, a singe goroutine allocates only 2kb  (!) . It can dynamically add more memory, but it will not waste it. </p>
<p><strong> How to implement a goroutine </strong></p>
<p>Now let's look at some code. Let's say I wan't to access a third party API to get some information. I need quite a bit of info, and I need it fast. Knowing that most of the time it takes to retrieve data from a simple HTTP request is spent waiting for the remote server to respond, I decide to use concurrency. </p>
<p>To make things simple , I will go step by step and first do it the synchronous way. First I need a function that sends an API call and returns the request body:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getData</span><span class="hljs-params">(url <span class="hljs-keyword">string</span>)</span> <span class="hljs-title">string</span></span> {
    r, err := http.Get(url)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        log.Fatal(err)
    }
    <span class="hljs-keyword">defer</span> r.Body.Close()
    body, err := ioutil.ReadAll(r.Body)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        log.Fatal(err)
    }
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">string</span>(body)
}
</code></pre><p>As we know the request , being a network call, can go wrong so I check for any errors.
I also call <code>defer r.Body.Close()</code> because that way we tell this function to close the request body after it is finished with it, same way we would close a file after reading it's content.</p>
<p>Finally, we assign a body variable the value returned from a call to the ioutil.ReadAll function, which takes a parameter that implements the io.Reader interface ( one that is implemented quite often in Go ) ,  and returns a byte array, which we can easily convert to a string afterwards.</p>
<p>Now let's call this function in our main function. I will use my favorite API , the Rick and Morty API, which I use in all of my examples ( luckily, not very many people implement the code from my articles, or this API server would be down 24/7) :</p>
<pre><code><span class="hljs-selector-tag">func</span> <span class="hljs-selector-tag">main</span>() {

    <span class="hljs-attribute">r </span>:= <span class="hljs-built_in">getData</span>(<span class="hljs-string">"https://rickandmortyapi.com/api/character/100"</span>)
    fmt.<span class="hljs-built_in">Println</span>(r)

}
</code></pre><p>So great, we got some info on character 100, who's name is very fortunate - "Bubonic Plague" . Nice. But, we actually need info on all of the Rick and Morty characters , not just Mr.Plague. And we don't want to wait tens or hundreds of seconds do get it, we need it now! <strong>Goroutines to the rescue</strong> :</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getDataFaster</span><span class="hljs-params">(url <span class="hljs-keyword">string</span>, c <span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)</span></span> {
    r, err := http.Get(url)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        log.Fatal(err)
    }
    <span class="hljs-keyword">defer</span> r.Body.Close()
    body, err := ioutil.ReadAll(r.Body)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        log.Fatal(err)
    }
    c &lt;- <span class="hljs-keyword">string</span>(body)
}
</code></pre><p>Whoa! That's not the syntax you expected , right? I mean , wtf is this arrow doing? And what is a chan? </p>
<p>In order for me to explain let me show you the version you expected, and how we would call it in the main function (  spoiler alert : it will not work as expected ) :</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

    <span class="hljs-keyword">for</span> i := <span class="hljs-number">1</span>; i &lt; <span class="hljs-number">200</span>; i++ {
        <span class="hljs-keyword">go</span> getDataFaster(<span class="hljs-string">"https://rickandmortyapi.com/api/character/"</span> + strconv.Itoa(i))

    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getDataFaster</span><span class="hljs-params">(url <span class="hljs-keyword">string</span>)</span></span> {
    r, err := http.Get(url)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        log.Fatal(err)
    }
    <span class="hljs-keyword">defer</span> r.Body.Close()
    body, err := ioutil.ReadAll(r.Body)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        log.Fatal(err)
    }
    fmt.Println(<span class="hljs-keyword">string</span>(body))
}
</code></pre><p>For now we modified the getDataFaster function only to print the result, and not return it. I'll explain why later. We also use a for loop to get all 200 characters ( there's actually more but we really don't want to spam it so much) . Since <code>i</code> is an integer, we will use the <code>strconv</code> built in module to convert it to a string.
Now, here's the cool part. We use the <code>go</code> keyword to tell the go compiler that we want this function to run asynchronously, meaning run so fast it seems all 200 function calls are running simultaneously. Unfortunately, when we run this, we find that it does nothing. </p>
<p>Well, now is about the time to leave a F U in the comments below.</p>
<p> Just kidding. </p>
<p>The reason this doesn't return anything is because the main function is essentially a goroutine of it's own, and it just went through the for loop and exited. It doesn't care that the other 200 goroutines haven't finished their job. It finished it's job and now wants to have a beer. </p>
<p>Enter channels!</p>
<p>Remember that bit of ugly code with the arrow and <code>chan</code>. Those are channels. A channel is essentially a place to store some value from our goroutine and enable another goroutine (our main function in this case) to get that value. That arrow at the end basically says - instead of returning the <code>string(body)</code> like you would in a regular function, jam it in a channel because this is no regular function, it's asynchronous.</p>
<p>Ok, but how does the main function then access these values you ask? Let's see in the next code snippet:</p>
<pre><code><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"fmt"</span>
    <span class="hljs-string">"io/ioutil"</span>
    <span class="hljs-string">"log"</span>
    <span class="hljs-string">"net/http"</span>
    <span class="hljs-string">"strconv"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {

    ch := <span class="hljs-built_in">make</span>(<span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)
    <span class="hljs-keyword">var</span> data []<span class="hljs-keyword">string</span>
    <span class="hljs-keyword">for</span> i := <span class="hljs-number">1</span>; i &lt; <span class="hljs-number">200</span>; i++ {
        <span class="hljs-keyword">go</span> getDataFaster(<span class="hljs-string">"https://rickandmortyapi.com/api/character/"</span>+strconv.Itoa(i), ch)
        data = <span class="hljs-built_in">append</span>(data, &lt;-ch)
    }
    fmt.Println(data)

}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getDataFaster</span><span class="hljs-params">(url <span class="hljs-keyword">string</span>, c <span class="hljs-keyword">chan</span> <span class="hljs-keyword">string</span>)</span></span> {
    r, err := http.Get(url)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        log.Fatal(err)
    }
    <span class="hljs-keyword">defer</span> r.Body.Close()
    body, err := ioutil.ReadAll(r.Body)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        log.Fatal(err)
    }
    c &lt;- <span class="hljs-keyword">string</span>(body)
}
</code></pre><p>Btw, this code includes all of the package and import declarations for folks who are just here for the copy/paste-ing . </p>
<p>As you can see, the first thing we do is declare a channel by using the built-in <code>make</code> function. A channel also needs to be statically typed , so we declare a channel that will hold only strings. Next, we declare a slice of strings called <em>data </em>where we plan to store all this info on all these wacky Rick and Morty characters.  We enter our for loop as before, but now we have this weird arrow again. This time the channel isn't the one that is on the receiving side , but rather seems to be the one that is sending . What we're doing here is appending the value that the channel will hold for us to our data slice. </p>
<p>This way we are initiating a blocking operation. This means that the main function will block until a value is actually gotten from the channel. This is how we make the main function wait , instead of carelessly exiting like it did the first time. </p>
<p>This is also the reason why we can't assign a value to a call to a goroutine ( I said I would explain later) , because it is asynchronous, and it will not return any value, it can only add it to a channel. </p>
<p>Finally, we print everything to the console, and since it's fetching 200 results , your console will probably blow up like mine:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633025722086/HY9Y6lBO8.png" alt="Screenshot from 2021-09-30 21-15-03.png" /></p>
<p>So there it is. A very elegant way of retrieving a lot of data very quickly by using goroutines and channels. </p>
<p>Hope you enjoyed. Thanks for reading!</p>
]]></content:encoded></item><item><title><![CDATA[String manipulation in Golang]]></title><description><![CDATA[Once you've learned enough syntax of a programming language, the best way to put in practice what you've learned so far is to start building an application. From my experience, for a very large number of applications ( web applications especially) th...]]></description><link>https://golongwithgolang.com/string-manipulation-in-golang</link><guid isPermaLink="true">https://golongwithgolang.com/string-manipulation-in-golang</guid><category><![CDATA[Go Language]]></category><category><![CDATA[string]]></category><category><![CDATA[data structures]]></category><category><![CDATA[functions]]></category><dc:creator><![CDATA[Pavle Djuric]]></dc:creator><pubDate>Sat, 25 Sep 2021 16:43:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1632587669389/Rgj1ZH2eQ.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Once you've learned enough syntax of a programming language, the best way to put in practice what you've learned so far is to start building an application. From my experience, for a very large number of applications ( web applications especially) the most common data type in the code is the <em>string</em> data type. </p>
<p>If you're building a web service , for example, a lot of the user input is going to be some type of text, and it will be passed either in the request body, the query string , or perhaps in the request headers. </p>
<p>So, working with strings is one of the most important parts of the job. </p>
<p>When working with strings in Go, for most of the operations you will need a module that is part of the Go standard library, and it is called - well, strings ( I like it when things are obvious) .</p>
<p>So let's look at some code snippets and explain what they do along the way:</p>
<pre><code><span class="hljs-selector-tag">package</span> <span class="hljs-selector-tag">main</span>

<span class="hljs-selector-tag">import</span> (
    "<span class="hljs-selector-tag">fmt</span>"
    "<span class="hljs-selector-tag">strings</span>"
)

<span class="hljs-selector-tag">func</span> <span class="hljs-selector-tag">main</span>() {

    <span class="hljs-attribute">fruits </span>:= <span class="hljs-string">"apple,orange,kiwi,peach"</span>
    fruitSlice := strings.<span class="hljs-built_in">Split</span>(fruits, <span class="hljs-string">","</span>)
    fmt.<span class="hljs-built_in">Println</span>(fruitSlice)
}
</code></pre><p>This one should be pretty straightforward.  Like every Go file, we start by specifying the package name and defining what we will import. Since we plan to run this file as an executable, we will put it in the main package, and define the main function.</p>
<p>I created a string called fruits, but I need it to be a slice. With the use of the strings module, a simple call of the Split function gives me the result I need. </p>
<p>Next, I want to see what my fruit string will look with all of the letters capitalized:</p>
<pre><code>capitalized := strings.ToUpper(fruits)
fmt.Println(capitalized)
</code></pre><p>Pretty easy. By now you've realized that the main difference between string manipulation in Go and an object oriented language like Python is that in Python we would call the split method directly on the string object e.g <code>fruits.split(',')</code></p>
<p>But, since Go is not an OOP language, you pass the string as a function parameter . It's basically just a different approach, but the result is quite similar. The function names are also pretty similar to ones that we know from manipulating strings in Python , JavaScript and other popular languages.  </p>
<p>Let's look at a couple of more examples that are common for working with strings. </p>
<p>Here we want to replace all occurrences of the word "Bucks" with the word "Lakers" ( my apologies to Bucks fans) . </p>
<pre><code>sentence := <span class="hljs-string">"The Bucks are the NBA champions. Go Bucks !"</span>
newSentence := strings.ReplaceAll(sentence, <span class="hljs-string">"Bucks"</span>, <span class="hljs-string">"Lakers"</span>)
fmt.Println(newSentence)
</code></pre><p>In the next one we are trimming the white space of a string, which is really useful when comparing two strings. I would always suggest trimming strings when comparing them, especially if the strings that are being compared are the result of splitting a larger string in to a slice of strings. I have witnessed a number of bugs in applications that were caused due to not trimming strings before comparing them.</p>
<pre><code>    <span class="hljs-comment">// lets compare the equality of two strings:</span>
    whiteSpacedSentence := <span class="hljs-string">"   Hello World   "</span>
    regularSentence := <span class="hljs-string">"Hello World"</span>
    <span class="hljs-keyword">if</span> whiteSpacedSentence == regularSentence {
        fmt.Println(<span class="hljs-string">"they're the same"</span>)
    } <span class="hljs-keyword">else</span> {
        fmt.Println(<span class="hljs-string">"they're NOT the same"</span>)
    }
    <span class="hljs-comment">// now let's trim the first string:</span>
    trimmedSentence := strings.TrimSpace(whiteSpacedSentence)
    <span class="hljs-keyword">if</span> trimmedSentence == regularSentence {
        fmt.Println(<span class="hljs-string">"they're the same"</span>)
    } <span class="hljs-keyword">else</span> {
        fmt.Println(<span class="hljs-string">"they're NOT the same"</span>)
    }
</code></pre><p>One last operation that I would like to mention concerned with strings is the conversion of different data types to strings. In Go, there are two approaches.</p>
<p>The first looks like this:</p>
<pre><code>byteSlice := []<span class="hljs-keyword">byte</span>{<span class="hljs-number">72</span>, <span class="hljs-number">101</span>, <span class="hljs-number">108</span>, <span class="hljs-number">108</span>, <span class="hljs-number">111</span>}
stringFromBytes := <span class="hljs-keyword">string</span>(byteSlice)
fmt.Println(stringFromBytes)
</code></pre><p>Here we have a byte slice containing some numbers and when you convert it to a string type you get a word that is used in english for greeting people. The numbers represent what the characters are in ASCII encoding when converted to bytes.</p>
<p>However, if you try this on an integer, the Go compiler will have an unpleasant message for you, in the manner of <code>conversion from int to string yields a string of one rune, not a string of digits</code> .  </p>
<p>Basically it is telling us that it will not convert the integer to a string , but rather to a rune, which is basically going to be its ASCII value. We don't want that, we just want a string , plain and simple. </p>
<p>Luckily, the Go standard library has a module that will solve this issue easily.
It's called strconv, and the function is called Itoa ( I know, they're not very descriptive, but remember the creators of Go were inspired in part by C and that's what it was called in C ) .</p>
<p>Here's the code:</p>
<pre><code>num := <span class="hljs-number">38</span>
numToString := strconv.Itoa(num)
fmt.Println(numToString)
</code></pre><p>That's it for this article. In the next articles I plan to write about more modules from the Go standard library that are essential for developing real applications. </p>
<p>Thanks for reading!</p>
]]></content:encoded></item><item><title><![CDATA[Is Go object oriented?]]></title><description><![CDATA[No , it is not. At least not in the way you’d expect. Go’s official documentation says this:
“
Yes and no. Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy. The concept of “interface” in...]]></description><link>https://golongwithgolang.com/is-go-object-oriented</link><guid isPermaLink="true">https://golongwithgolang.com/is-go-object-oriented</guid><category><![CDATA[Go Language]]></category><category><![CDATA[oop]]></category><category><![CDATA[data structures]]></category><dc:creator><![CDATA[Pavle Djuric]]></dc:creator><pubDate>Wed, 22 Sep 2021 18:19:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1632330633935/QND0RX5dD.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>No , it is not. At least not in the way you’d expect. Go’s official documentation says this:</p>
<p>“
Yes and no. Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy. The concept of “interface” in Go provides a different approach that we believe is easy to use and in some ways more general. There are also ways to embed types in other types to provide something analogous—but not identical—to subclassing. Moreover, methods in Go are more general than in C++ or Java: they can be defined for any sort of data, even built-in types such as plain, “unboxed” integers. They are not restricted to structs (classes). </p>
<p>Also, the lack of a type hierarchy makes “objects” in Go feel much more lightweight than in languages such as C++ or Java.”</p>
<p>Technically, Go implements some object oriented functionality (e.g interfaces, polymorphism) , but it doesn’t actually implement objects . </p>
<p>What?? You mean a language built in the 21st century, that is gaining so much popularity is not really object oriented? </p>
<p>Yes. However, it does implement something similar, so don't worry. If you come from an OOP language like Java or Python, it won't take long before you're comfortable with Go.</p>
<p>The creators of Go wanted to keep things as simple as possible, and inheritance and polymorphism do tend to complicate matters from time to time. </p>
<p>They didn't really come up with anything new to be honest. They took a concept that is pretty old and modified it a bit. </p>
<p><strong>Structs</strong></p>
<p>Anyone who ever programmed in C  has probably heard of structs. But if you're coming from JavaScript, Python or even Java , you probably haven't.</p>
<p>Structs are simmilar to classes, except they don't have methods, and you can't extend them. Then again, they kind of do have methods.. and you kind of can extend them. 
Ok, before you start cursing and leaving negative comments, time do demonstrate what I mean.</p>
<p>A typical struct is written like this :</p>
<pre><code><span class="hljs-keyword">type</span> Animal <span class="hljs-keyword">struct</span> {

    latinName <span class="hljs-keyword">string</span>
    continentOfOrigin <span class="hljs-keyword">string</span>
    isExtinct <span class="hljs-keyword">bool</span>

}
</code></pre><p>Looks a bit familiar? When we define a class in Java, we use a similar syntax, no? Except instead of the <code>type Animal struct</code> we would say <code>class Animal</code> .
string and bool are obviously the data types, since we know that Go is a statically typed language. </p>
<p>Now, I said that Go structs don't have methods, but then I sort of changed my mind. Well, here's the Go way of writing a "method" :</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(a Animal)</span> <span class="hljs-title">hasLongName</span><span class="hljs-params">()</span> <span class="hljs-title">bool</span></span> {
    <span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(a.latinName) &gt; <span class="hljs-number">10</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>
    }
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
}
</code></pre><p>Let me elaborate on the above code snippet. The first keyword <code>func</code> is the way we define any function in Go (think <code>def</code> in Python) . Now this <code>(a Animal)</code> is interesting. It is the <em>function receiver</em> . If a function has a receiver, then it is sort of like a method would be in an OOP language. <code>hasLongName</code> is the name of the function and <code>bool</code> is what data type it will return. A receiver function means we can do something like this:</p>
<pre><code><span class="hljs-selector-tag">func</span> <span class="hljs-selector-tag">main</span>() {

    <span class="hljs-attribute">a </span>:= Animal{<span class="hljs-string">"Canis familiaris"</span>, <span class="hljs-string">"Europe"</span>, false}
    <span class="hljs-selector-tag">fmt</span><span class="hljs-selector-class">.Println</span>(<span class="hljs-selector-tag">a</span><span class="hljs-selector-class">.hasLongName</span>()) 
}
</code></pre><p>Notice how we use the dot operator , like we would in any OOP language when calling a method? That surely makes things a bit more familiar to Java or Python. 
Also, notice how we instantiate the struct with the curly braces. In an OOP language, we would probably use paretheses. No <code>new</code> keyword either, but if you're coming from Python you're used to this. </p>
<p>Anyway, this hopefully explains the whole <em>"Go doesn't have methods, but actually it does" </em> ordeal I was rambling about before. </p>
<p>Now, I also said that there is no inheritance, and that is absolutely true. But , there is something similar. It's called composition, and it's also nothing new. Java has a number of design patterns depending directly on this concept. Basically, it's something like this:</p>
<pre><code><span class="hljs-comment">// first let's define the Dog struct</span>
<span class="hljs-keyword">type</span> Dog <span class="hljs-keyword">struct</span> {
    Animal
    name   <span class="hljs-keyword">string</span>
    gender <span class="hljs-keyword">string</span>
    size   <span class="hljs-keyword">string</span>
}

<span class="hljs-comment">// now let's instantiate it in the main function</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>{
     d := Dog{Animal: Animal{<span class="hljs-string">"Canis"</span>, <span class="hljs-string">"Europe"</span>, <span class="hljs-literal">false</span>}, name: <span class="hljs-string">"Fluffy"</span>, gender: <span class="hljs-string">"Male"</span>, size: <span class="hljs-string">"Small"</span>}
<span class="hljs-comment">//(By the way, notice how you can also define a struct with colons ,like here)</span>
    fmt.Println(d.isExtinct)
    fmt.Println(d.name)
    fmt.Println(d.hasLongName())
}
</code></pre><p>So, what I did was instead of saying something like <code>Dog extends Animal</code> like you would see in Java, I just added Animal as a field , and the Dog type now sort of <em> inherited </em> all of it's fields.  This looks relatively simple, right?</p>
<p>There's one thing I would like to stress here. It has to do with a topic I will cover in a separate article, but I feel I should mention it here. The reason is, since you saw how easy it is to write a receiver function, you might be inclined to start writing your own and maybe you'll try something like this:</p>
<pre><code>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(d Dog)</span> <span class="hljs-title">changeSize</span><span class="hljs-params">(newSize <span class="hljs-keyword">string</span>)</span></span> {
    d.size = newSize
}


d := Dog{Animal: Animal{<span class="hljs-string">"Canis"</span>, <span class="hljs-string">"Europe"</span>, <span class="hljs-literal">false</span>}, name: <span class="hljs-string">"Fluffy"</span>, gender: <span class="hljs-string">"Male"</span>, size: <span class="hljs-string">"Small"</span>}
d.changeSize(<span class="hljs-string">"Medium"</span>)
fmt.Println(d.size)
</code></pre><p>If you're using a good text editor, it will probably already ask you wtf you are doing.
If not, I'll tell you - this snippet of code will not work as intended.</p>
<p>You see, Go is a <em>pass by value</em> language, as opposed to most popular languages you are probably used to which are mostly <em>pass by reference</em>. This means that the <code>d Dog</code> is not going to be good ol' Fluffy that we instantiated a few lines above. It's going to be a new Dog, a sort of clone of Fluffy, but our original Fluffy won't really care. </p>
<p>So how do we actually acknowledge that our original Fluffy has gained a few pounds and is now a medium puppy? </p>
<p>Enter pointers.</p>
<p>Now, like I said, it is a topic that is probably one of the most complex to understand in Go (once again, if you are coming from C, you are probably laughing at me) . So, I won't go into too much detail but for now I'll just share this code and try to explain a bit:</p>
<pre><code>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(d *Dog)</span> <span class="hljs-title">changeSize</span><span class="hljs-params">(newSize <span class="hljs-keyword">string</span>)</span></span> {
    d.size = newSize
}


d := Dog{Animal: Animal{<span class="hljs-string">"Canis"</span>, <span class="hljs-string">"Europe"</span>, <span class="hljs-literal">false</span>}, name: <span class="hljs-string">"Fluffy"</span>, gender: <span class="hljs-string">"Male"</span>, size: <span class="hljs-string">"Small"</span>}
d.changeSize(<span class="hljs-string">"Medium"</span>)
fmt.Println(d.size)
</code></pre><p>If you are saying to yourself: "This looks an awful lot like the code that didn't work. " Yes, you are right. Except for the <code>*</code> in front of Dog. Basically it is telling the function that you want to access the values of that particular Dog. Not any clone , but the real Fluffy. For now, it is good to remember it like that. For the future, it is best to wait for my article on pointers, or better yet you can google it now and find a lot of quality articles and videos on the subject .</p>
<p>I hope this clears up as to why Go is not an object oriented language, but also why it isn't that hard to transition from OOP classes to Go structs.</p>
<p>Thanks for reading, and see you in the next one!</p>
]]></content:encoded></item><item><title><![CDATA[What's so unique about Golang syntax?]]></title><description><![CDATA[Golang is pretty simple to read and write, but when you first see some code snippets of it, some of it’s syntax looks a bit weird. However, once you get acquainted with how it works, you’ll realize how neat this syntax actually is. 
I’d like to go ov...]]></description><link>https://golongwithgolang.com/whats-so-unique-about-golang-syntax</link><guid isPermaLink="true">https://golongwithgolang.com/whats-so-unique-about-golang-syntax</guid><category><![CDATA[Go Language]]></category><category><![CDATA[programming languages]]></category><dc:creator><![CDATA[Pavle Djuric]]></dc:creator><pubDate>Sun, 19 Sep 2021 09:52:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1632335003802/mnkD6ZZW6.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Golang is pretty simple to read and write, but when you first see some code snippets of it, some of it’s syntax looks a bit weird. However, once you get acquainted with how it works, you’ll realize how neat this syntax actually is. </p>
<p>I’d like to go over some syntax that you will find in the Go programming language, that you probably won’t see in other popular languages.</p>
<p><strong>1. Implicit type declaration 
</strong></p>
<p>Since Go is statically typed, you need to declare the type of the variable when defining it. So, if you want to create a variable called city of type string with the value "Miami", you write:</p>
<pre><code><span class="hljs-keyword">var</span> city <span class="hljs-keyword">string</span> = <span class="hljs-string">"Miami"</span>
</code></pre><p>Pretty simple right? But , when reading Go code, you usually won't see it like this. What you will see more often is :</p>
<pre><code>city := <span class="hljs-string">"Miami"</span>
</code></pre><p>The := operator (also known in Python as the walrus operator) is used for type inference so that you don't have to declare the type, since it is pretty obvious from it's value that it is a string. </p>
<p>This isn't something Go has invented. Java and C# have implemented this long ago, but instead of using := , they both use the var keyword. This way of using type inference is pretty unique.</p>
<p><strong>2. For loops used instead of while </strong></p>
<p>This looks kind of weird the first time you see it. Let's say you need an endless loop . In most programming languages you would write something like : <code>while true { ... }</code> .
Not in Go however. Go actually doesn't even recognize the <strong>while</strong> keyword.  The reason for this is that the creators of Go really wanted to keep it as minimal as possible . As a result, Go has only 25 keywords  ( Java has 61 ) . </p>
<p>So how do you create an endless loop  in Go? One word - <strong>for</strong> .
Want your terminal to write "Hello" endlessly? ( obviously not the cleverest reason for using and endless loop )  Here's the syntax :</p>
<pre><code><span class="hljs-selector-tag">for</span> {
        <span class="hljs-selector-tag">fmt</span><span class="hljs-selector-class">.Println</span>(<span class="hljs-string">"Hello"</span>)
    }
</code></pre><p>When you think about it, <strong>for</strong> is predominantly used for iterating over collections, someting you will be doing a lot as a developer. <strong>while</strong> however, is usually used much less often, so why not just merge the two keywords into one.</p>
<p><strong>3. Error handling </strong></p>
<p>You are writing a program that needs to call a third party API. You are aware that your program now depends not only on your code, but on some server god knows where being maintained by god knows who. To make sure your app doesn't crash, you'd better put the code that sends the HTTP request in a try/catch block (or try/except for my fellow Pythonistas) . Well, Golang is not going to be cooperative about that. </p>
<p>You see, there is no try/catch in Go. </p>
<p>Wait, so Go apps crash all the time, right?</p>
<p>Nope. </p>
<p>Go has  (like many languages) the possibility of returning multiple values from a function call. Instead of writing try/catch , Go enables the developer to check if one of the returned values is an error. Let's see how this looks in practice: </p>
<pre><code>resp, err := http.<span class="hljs-keyword">Get</span>("https://someExternalApi.com")
<span class="hljs-keyword">if</span> err != nil {
   <span class="hljs-keyword">log</span>.Fatalln(err)
}
</code></pre><p>You will be seeing a whole lot of this in Go. I remember when I first saw a large Go code base, it was full of these <code>if err !=nil</code> snippets. It felt like literally 80% of the code. Well, that's how you handle errors in Go. And, it's really useful, because it forces you to check for errors.  </p>
<p>Forces me? What are you talking about? </p>
<p>If you don't believe me try this: </p>
<pre><code>resp := http.<span class="hljs-keyword">Get</span>("https://someExternalApi.com")
</code></pre><p>The Go compiler will refuse to run it. The http.Get method retuns two values , the latter being the error. If you don't define two values, the compiler will say someting like :
<em>cannot initialize 1 variables with 2 values</em></p>
<p>Ok, so what? You will define the error , but how does that force you to actually do anything with it? Well, in Golang, defining a variable and not using it is impossible. </p>
<p>If you write :</p>
<pre><code>resp,err := http.Get(<span class="hljs-string">"https://someExternalApi.com"</span>)
fmt.Println(resp.Status) <span class="hljs-comment">// this will just print out the response status code</span>
</code></pre><p>the compiler will say : <em>err declared but not used</em></p>
<p>The reason for this is that the Go compiler is incredibly pragmatic. It doesn't like monkey business like unused imports or variables, because these will make the compiler seem slow and the binaries that it produces will seem bloated. The speed at which the Go compiler produces it's lean binaries is truly a thing of beauty.   </p>
<p>Now, if you are really stubborn, and just don't want to handle the damn error, you can do something like this:</p>
<pre><code>resp, _ := http.<span class="hljs-keyword">Get</span>("https://someExternalApi.com")
fmt.Println(resp.Status)
</code></pre><p>The <strong>_ </strong>character tells the compiler that you are aware that this function returns two values but you only want to use the first one. At this point the compiler gives up on lecturing you about error handling, but when your app crashes , at least you can't say that it didn't do it's best to warn you. </p>
<p><strong> 4. The gorountine </strong></p>
<p>Goroutines are a topic that deserve it's own article, which I will definitely be writing in the future. For now, I just want you to get acquainted with the syntax so you don't get confused when you see it. </p>
<p>Let's say we are going to be calling a lot of different external APIs in our app. Logically, we want to wrap the above code in a function, so we don't need to rewrite every line for every API call. Let's do that first:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getApiResponse</span><span class="hljs-params">(url <span class="hljs-keyword">string</span>)</span></span> {
    resp, err := http.Get(url)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        log.Fatal(err)  <span class="hljs-comment">// notice how I'm being responsible about error handling :)</span>
    }
    fmt.Println(resp.Status) 
}
</code></pre><p>Great. But, wait. My app sometimes needs to send 500 API calls to get some information. How do I do this. Maybe this? :</p>
<pre><code>urls := []<span class="hljs-keyword">string</span>{<span class="hljs-string">"url1"</span>,<span class="hljs-string">"url2"</span>,<span class="hljs-string">"url3"</span>} <span class="hljs-comment">//this is a slice of strings containing all the urls</span>
<span class="hljs-keyword">for</span> _, url := <span class="hljs-keyword">range</span> urls { 
        getApiResponse(url)
        }
</code></pre><p>(  here I am using _ because the first return value of the range is an index, which I really do not need )</p>
<p>Well this would be ok , right?</p>
<p>Well, not really. The problem with this approach is that the requests will be sent synchronously , meaning one after the other. This can take quite a while. What you want is a way to send them concurrently. Enter gorountines. Like I said , explaining goroutines in detail will go into it's own article, but for now here is the syntax:</p>
<pre><code>urls := []<span class="hljs-keyword">string</span>{<span class="hljs-string">"url1"</span>,<span class="hljs-string">"url2"</span>,<span class="hljs-string">"url3"</span>} 
<span class="hljs-keyword">for</span> _, url := <span class="hljs-keyword">range</span> urls {
        <span class="hljs-keyword">go</span> getApiResponse(url)
        }
</code></pre><p>That's it! You just add the <strong>go</strong> keyword if front of your function call, and watch the execution time drop enormously. </p>
<p>One thing to note if you actually run this snippet :</p>
<p>(actually two things - the first being that if you really want a response , enter valid urls instead of the "url1","url2" placeholders )</p>
<p>You won't actually see the response, because the main function will finish execution before to goroutines are done. This is where it gets a bit complex, and explaining it fully would require introducing the concept of <em>channels</em> . I won't do this right now, but if you really want to see a return value immediately you can do this:</p>
<pre><code>urls := []<span class="hljs-keyword">string</span>{<span class="hljs-string">"url1"</span>,<span class="hljs-string">"url2"</span>,<span class="hljs-string">"url3"</span>}
<span class="hljs-keyword">for</span> _, url := <span class="hljs-keyword">range</span> urls { 
        <span class="hljs-keyword">go</span> getApiResponse(url)
        time.Sleep(time.Millisecond * <span class="hljs-number">100</span>)
    }
</code></pre><p>This will make the main function wait for 100 milliseconds, thus giving the goroutine time to return the value before the main function exits. This usually isn't the way you would do it in a real app, but for the sake of simplicity , it will do for now. </p>
<p>That's all for this article, I hope you learned something new. </p>
<p>Thanks for reading, and see you in the next one!</p>
]]></content:encoded></item><item><title><![CDATA[Why I started learning Golang]]></title><description><![CDATA[Hello! Welcome to the very first article in the “Go Long with Golang” blog. My name is Pavle , and I am a Python developer, who has recently decided to learn Go. 
For my first article I will keep it simple and brief, and just try to name a few reason...]]></description><link>https://golongwithgolang.com/why-i-started-learning-golang</link><guid isPermaLink="true">https://golongwithgolang.com/why-i-started-learning-golang</guid><category><![CDATA[Go Language]]></category><category><![CDATA[programming languages]]></category><dc:creator><![CDATA[Pavle Djuric]]></dc:creator><pubDate>Fri, 17 Sep 2021 06:24:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1632335092729/-fz3XPPcq.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello! Welcome to the very first article in the “Go Long with Golang” blog. My name is Pavle , and I am a Python developer, who has recently decided to learn Go. </p>
<p>For my first article I will keep it simple and brief, and just try to name a few reasons why I decided to start learning Go:</p>
<ol>
<li><p>The first reason , to be completely honest , is driven by pure greed :) . I think Go is going to be truly dominant in the coming years, and the demand for Go developers is going to explode pretty soon. It was built for the 21st century, made to work great with 21st century technologies such as the Cloud and multi-core processors.</p>
</li>
<li><p>It compiles to a single binary that runs machine code. This means that to run a Go app, you do not need any interpreter or virtual machine intermediary like you do for Python or Java. This further means that when putting your Go app in a container, you can use the “Scratch” base image. The result is a very lean Docker image usually no larger than 20MBs . An average Python image is at least 10-15 times larger.</p>
</li>
<li><p>The compile time is ridiculously fast. I’ve never worked on a Java app that has hundreds of thousands of lines of code, but I hear that compiling it can take quite a while. Legend says that the Game room (which as we know almost all tech companies now have on prem )was invented because developers had nothing to do while waiting for their Java apps to compile. Another legend says that the creators of Go , wrote the entire language while waiting for their apps written in other languages to compile.</p>
</li>
<li><p>Speaking of the creators of Go, they are three of the most legendary members of the tech community, people that have been part of major projects that are still
used even though they have been created around half a century ago. 
Ken Thompson, one of the creators, is the author of Unix , the operating system that inspired the creation of Linux, which is the OS that runs over 90% of all servers today. He also assisted the development of C , the mother of most modern programming languages. When you add the fact that Go is backed by Google, I think it is safe to say that everyone involved in it’s development knows what they’re doing.</p>
</li>
<li><p>Finally (and I know it’s a cliche) , the language is so damn simple. It’s small and if you take a 7-8 hour couse of it ( there is a number of good ones online) , you will be able to start building real apps pretty soon. As a Python developer, I like to keep it simple. Golang has the simplicity of Python , and the power of C . Software such as Kubernetes, Docker, CockroachDB and Terraform were made in Go . </p>
</li>
</ol>
<p>I hope these reasons are compelling enough for you as they were for me. </p>
<p>In this blog I will document my leaning path , mostly because I think I will learn even better by sharing what I have discovered.</p>
<p>Thanks for reading, and I hope you will join me on this path!</p>
]]></content:encoded></item></channel></rss>