<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shayan khan on Medium]]></title>
        <description><![CDATA[Stories by Shayan khan on Medium]]></description>
        <link>https://medium.com/@shayannoor123khan?source=rss-7ff7983dc83e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YkMisw03lqthsS-5Tr6lAg@2x.jpeg</url>
            <title>Stories by Shayan khan on Medium</title>
            <link>https://medium.com/@shayannoor123khan?source=rss-7ff7983dc83e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 13:12:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shayannoor123khan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Golang and Cloud security, a match made in heaven?]]></title>
            <link>https://medium.com/@shayannoor123khan/golang-and-cloud-security-a-match-made-in-heaven-171745efe8eb?source=rss-7ff7983dc83e------2</link>
            <guid isPermaLink="false">https://medium.com/p/171745efe8eb</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cloud-security]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Shayan khan]]></dc:creator>
            <pubDate>Mon, 03 Apr 2023 21:21:17 GMT</pubDate>
            <atom:updated>2023-04-03T21:21:17.228Z</atom:updated>
            <content:encoded><![CDATA[<p>In recent years, cloud computing has become an integral part of many businesses’ IT infrastructure. While the cloud offers many benefits, such as cost savings and scalability, it also poses security risks. To mitigate these risks, businesses must take steps to secure their cloud environments. One effective approach to securing clouds is using the programming language Golang.</p><p>Golang, also known as Go, is an open-source programming language developed by Google. It is known for its simplicity, efficiency, and strong support for concurrent programming. These features make Golang an excellent choice for developing secure cloud applications.</p><p>Here are some tips for using Golang to secure your cloud environments:</p><ol><li>Use secure coding practices: When developing cloud applications using Golang, it is essential to use secure coding practices. This includes input validation, proper error handling, and secure coding patterns such as the principle of least privilege. By following these practices, you can prevent common security vulnerabilities such as SQL injection and cross-site scripting attacks.</li><li>Use encryption: Encryption is an essential part of securing data in the cloud. Golang provides robust encryption libraries, such as the Crypto package, which can be used to encrypt data at rest and in transit. By encrypting data, you can protect it from unauthorized access, theft, and interception.</li><li>Implement access controls: Access controls are essential for securing cloud environments. Golang provides several libraries that can be used to implement access controls, such as the ACL package. By implementing access controls, you can restrict access to sensitive data and prevent unauthorized users from accessing your cloud applications.</li><li>Use secure communication protocols: When communicating with cloud services, it is essential to use secure communication protocols such as HTTPS. Golang provides support for HTTPS through the net/http package, which can be used to build secure web applications. By using secure communication protocols, you can protect sensitive data from interception and ensure the integrity of data in transit.</li><li>Regularly update dependencies: When developing cloud applications using Golang, it is essential to keep your dependencies up to date. This includes updating Golang itself, as well as any third-party libraries used in your applications. By keeping your dependencies up to date, you can ensure that your applications are not vulnerable to known security vulnerabilities.</li></ol><p>In conclusion, securing cloud environments is a crucial part of ensuring the confidentiality, integrity, and availability of data in the cloud. By using Golang and following these best practices, businesses can develop secure cloud applications that protect their data from unauthorized access and theft.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=171745efe8eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go(ing) queued: Writing queues in Golang]]></title>
            <link>https://medium.com/@shayannoor123khan/go-ing-queued-writing-queues-in-golang-8bdf5bc0b9bb?source=rss-7ff7983dc83e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bdf5bc0b9bb</guid>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[queue-management]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Shayan khan]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 22:19:13 GMT</pubDate>
            <atom:updated>2023-04-02T22:19:13.535Z</atom:updated>
            <content:encoded><![CDATA[<h3>Go(ing) queued: Writing queues in Golang.</h3><p>Go is a programming language that was designed with concurrency in mind. One of the key tools for managing concurrency in Go is the use of channels, which allow goroutines to communicate with each other in a synchronized way. Another important tool is the use of queues, which can be used to manage tasks or events in a concurrent program. In this article, we will explore how to write queues in Go.</p><p>Queues are a fundamental data structure in computer science that allow you to store and retrieve data in a first-in, first-out (FIFO) order. This is useful when you have a set of tasks or events that need to be processed in order. A queue is typically implemented using a linked list or an array.</p><p>In Go, you can implement a queue using a channel. A channel is a typed conduit through which you can send and receive values with the channel operator, &lt;-. Channels can be buffered, meaning that they can hold a certain number of values before they are blocked. If a channel is unbuffered, then it can only hold one value at a time, and the sender will block until the receiver is ready to receive the value.</p><p>To implement a queue using a channel, you can create a buffered channel with a certain capacity. You can then send values to the channel to add them to the queue, and receive values from the channel to remove them from the queue. Here’s an example implementation of a queue using a channel in Go:</p><pre> <br>package main <br>import &quot;fmt&quot; <br>func main() <br>{ <br>  q := make(chan int, 5) // create a buffered channel with capacity 5<br>  // add values to the queue <br>  q &lt;- 1 q &lt;- 2 q &lt;- 3 // remove values from the queue <br>  fmt.Println(&lt;-q) <br>  fmt.Println(&lt;-q) <br>  fmt.Println(&lt;-q) <br>}</pre><p>In this example, we create a buffered channel q with a capacity of 5. We then add three values to the channel using the channel operator &lt;-. Finally, we remove the values from the channel using the channel operator &lt;-, which blocks until a value is available to be received.</p><p>This implementation of a queue using a channel is simple and effective, but it has some limitations. For example, if you want to remove a value from the middle of the queue, you have to first remove all the values before it. This can be inefficient if the queue is large.</p><p>To address this limitation, you can implement a more complex queue using a doubly-linked list. A doubly-linked list is a data structure that allows you to efficiently insert and remove values from anywhere in the list. Here’s an example implementation of a doubly-linked list queue in Go:</p><pre>package main <br>import &quot;fmt&quot; <br><br>type Node struct {<br> value int prev<br> *Node next *Node <br>} <br><br>type Queue struct { <br>head *Node <br>tail *Node<br>}<br><br>func (q *Queue) Enqueue(value int) { <br>node := &amp;Node{value: value} <br>if q.head == nil { <br>q.head = node q.tail = node <br>} else { node.prev = q.tail q.tail.next = node q.tail = node } } <br><br>func (q *Queue) Dequeue() int { <br>if q.head == nil { <br>return 0 <br>} <br>value := q.head.value <br>q.head = q.head.next <br>if q.head == nil { <br>q.tail = nil <br>} else { q.head.prev = nil } <br>return value <br>} <br><br>func main() {<br>q := &amp;Queue{} // add values to the queue <br>q.Enqueue(1)<br>}</pre><p>That was all about queues in Go.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bdf5bc0b9bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to properly log in Go?]]></title>
            <link>https://medium.com/@shayannoor123khan/how-to-properly-log-in-go-435e870c0637?source=rss-7ff7983dc83e------2</link>
            <guid isPermaLink="false">https://medium.com/p/435e870c0637</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Shayan khan]]></dc:creator>
            <pubDate>Sun, 27 Nov 2022 12:07:29 GMT</pubDate>
            <atom:updated>2022-11-27T12:07:29.188Z</atom:updated>
            <content:encoded><![CDATA[<p>For this article, we will be focusing on the log package in Golang. This package implements simple structs, methods and functions to log program runtime info. But first we need to evaluate as to why the “fmt” package should not be used:</p><ul><li>The log package is concurrently safe from goroutines while the fmt package is not.</li><li>Log package can automatically attach information regarding time, date, file path, etc.</li></ul><p>The first point means that if are using the fmt package across multiple processes the message may not come out as expected.</p><p>Let’s start by writing a simple log message:</p><pre>package main<br><br>import &quot;log&quot;<br><br>func main() {<br> log.Println(&quot;test log&quot;)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BvpVuEpTxDsHJZVSBhvEVQ.png" /></figure><p>This shows how a simple message can be displayed in Go. We can also set flags of what kind of log flags should be attached to the message :</p><pre>package main<br><br>import &quot;log&quot;<br><br>func main() {<br> log.SetFlags(log.Ldate | log.Lshortfile)<br> log.Println(&quot;test log&quot;)<br>}</pre><p>This will only display the date along with the file name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*or7kWuALKVjUvpw9Vzp_Ng.png" /></figure><p>We can also call the panic function through this package :</p><pre>package main<br><br>import &quot;log&quot;<br><br>func main() {<br> //log.SetFlags(log.Ldate | log.Lshortfile)<br> //log.Println(&quot;test log&quot;)<br> log.Panic(&quot;Panicing&quot;)<br>}<br></pre><p>This will give the following output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dHiLPMX35RYvGEgUTsUzfA.png" /></figure><p>If we want the program to end in case of an error we do something like this,</p><pre>package main<br><br>import &quot;log&quot;<br><br>func main() {<br> //log.SetFlags(log.Ldate | log.Lshortfile)<br> //log.Println(&quot;test log&quot;)<br> //log.Panic(&quot;Panicing&quot;)<br> log.Fatal(&quot;fatal...&quot;)<br>}</pre><p>This will give the following output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cxE0OPt9yH39EZs4oNWqmw.png" /></figure><p>We usually log these messages inside a file :</p><pre>package main<br><br>import (<br> &quot;log&quot;<br> &quot;os&quot;<br>)<br><br>func main() {<br> //log.SetFlags(log.Ldate | log.Lshortfile)<br> //log.Println(&quot;test log&quot;)<br> //log.Panic(&quot;Panicing&quot;)<br> //log.Fatal(&quot;fatal...&quot;)<br> file, _ := os.Create(&quot;file.log&quot;)<br> log.SetOutput(file)<br> log.Println(&quot;hello world&quot;)<br> file.Close()<br>}</pre><p>This will not print anything on the terminal instead it will give its output in the file :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RUtVbBY0cGx6tSp5--Wf1A.png" /></figure><p>You can observe the file below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axlENlbN-vsrdKAqT2eEdA.png" /></figure><p>There are some common logs that we usually use :</p><pre>package main<br><br>import (<br> &quot;log&quot;<br> &quot;os&quot;<br>)<br><br>func main() {<br> //log.SetFlags(log.Ldate | log.Lshortfile)<br> //log.Println(&quot;test log&quot;)<br> //log.Panic(&quot;Panicing&quot;)<br> //log.Fatal(&quot;fatal...&quot;)<br> //file, _ := os.Create(&quot;file.log&quot;)<br> //log.SetOutput(file)<br> //log.Println(&quot;hello world&quot;)<br> //file.Close()<br><br> flags := log.Ldate | log.Lshortfile<br> infoLogger := log.New(os.Stdout, &quot;INFO: &quot;, flags)<br> warnLogger := log.New(os.Stdout, &quot;WARN: &quot;, flags)<br> errorLogger := log.New(os.Stdout, &quot;ERROR: &quot;, flags)<br> infoLogger.Println(&quot;This is an info log&quot;)<br> warnLogger.Println(&quot;This is an warning log&quot;)<br> errorLogger.Println(&quot;This is an error log&quot;)<br>}</pre><p>This will give the following output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gru44FxqdE9DHo1CzsJXRQ.png" /></figure><p>We can also create an aggregated loggers which we will discuss in some other article, so this was it regarding logging in Go.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=435e870c0637" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang Defers: Delaying the execution of a function in Go.]]></title>
            <link>https://medium.com/@shayannoor123khan/golang-defers-delaying-the-execution-of-a-function-in-go-a9446a173b3e?source=rss-7ff7983dc83e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9446a173b3e</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Shayan khan]]></dc:creator>
            <pubDate>Wed, 23 Nov 2022 19:03:58 GMT</pubDate>
            <atom:updated>2022-11-23T19:03:58.111Z</atom:updated>
            <content:encoded><![CDATA[<p>Whenever a function executes,it executes the statements line by line.For example:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br> fmt.Println(&quot;Hello&quot;)<br> fmt.Println(&quot;World&quot;)<br>}</pre><p>The output is achieved as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g6Z3eZ2It0m8REDHlUgw-A.png" /></figure><p>Taking this code snippet as an example, whenever the main function is executed, it prints Hello first and then it prints world, but what if we want to avoid this regular program execution, we can acheive this by using the defer keyword that is provided by Go.</p><p>This defer keyword <strong>delays the execution of the function or method or an anonymous method until the nearby functions returns. </strong>This can be explained in a simple way using an example:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br> defer fmt.Println(&quot;Hello&quot;)<br> fmt.Println(&quot;World&quot;)<br>}</pre><p>This would produce the output as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FT8oBrIj8hXs9mlKJJS9oQ.png" /></figure><p>This shows what magic the defer keyword has done, this has delayed the execution of the statement till the end. But what if there are multiple defe statements in the program, this will cause all the defers statements to be executed in LIFO order. For example:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br> defer fmt.Println(&quot;one&quot;)<br> defer fmt.Println(&quot;two&quot;)<br> defer fmt.Println(&quot;three&quot;)<br>}</pre><p>This will give the following output which depicts how multiple defer statements are handled:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vtZd1UHMTW7i3OQoR6XxiA.png" /></figure><p>We can also use defer statements within a function:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br> defer fmt.Println(&quot;one&quot;)<br> defer fmt.Println(&quot;two&quot;)<br> defer fmt.Println(&quot;three&quot;)<br> deferred()<br>}<br><br>func deferred() {<br> for i := 0; i &lt; 5; i++ {<br>  defer fmt.Println(i)<br> }<br>}</pre><p>This will give the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gGOaGvz6msNhzkb45-BHlA.png" /></figure><p>So, this is how defers can be used in Golang.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9446a173b3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Golang prefers composition over inheritance?]]></title>
            <link>https://medium.com/@shayannoor123khan/why-golang-prefers-composition-over-inheritance-c0eff45c2df3?source=rss-7ff7983dc83e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0eff45c2df3</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[inheritance]]></category>
            <dc:creator><![CDATA[Shayan khan]]></dc:creator>
            <pubDate>Sun, 06 Nov 2022 12:06:32 GMT</pubDate>
            <atom:updated>2022-11-06T12:06:32.345Z</atom:updated>
            <content:encoded><![CDATA[<p>Go is usually touted to be an object oriented language but it is just something else behind the scenes. Normally, in object oriented languages inheritance is used but in Go composition is preferred, here is why:</p><p><strong>Problems with inheritance:</strong></p><p>(i) Large hierarchies (ii) Tight coupling</p><p>Let’s discuss about inheritance:</p><p><strong>Inheritance:</strong></p><p>It corresponds to “is a” relationships. Let’s take an example of an animal which has the attributes of eating and sleeping, So, the possible inherited classes from animal can be dog, person and fish. The current attributes may go well along the inherited classes but if an attribute of walking is added to the current attributes, do you think this would go along well , the simple answer to it is “No” as the fish has no ability to walk, one simple solution could be to make categories for each type if we still want to use inheritance. It would look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*6BI04UV7cA1k9c3Sv9gtzw.png" /></figure><p>The problem with this is that every time we want to add a new attribute, we would have to append it to the already defined classes. This is where composition comes in:</p><p><strong>Composition:</strong></p><p>It corresponds to “has a” relationship. Now we can define the attributes in such a way that the animal has the ability to stay “alive” which means it can eat and sleep , also we can define the attributes walkable and swimmable depending on what ability the animal should have. As maintaining “has a” relationships is easier than maintaining “is a” relationships, that is why composition is preferred in Go.</p><p>Here is how composition can be implemented in Go:</p><pre>package main<br></pre><pre>import &quot;fmt&quot;<br></pre><pre>type alive struct {<br>}</pre><pre>type walkable struct {<br>}</pre><pre>type swimable struct {<br>}</pre><pre>type duck struct {<br>a alive<br>w walkable<br>s swimable<br>}</pre><pre><br>func (d duck) eat() {<br>d.a.eat()<br>}</pre><pre>func (d duck) sleep() {<br>d.a.sleep()<br>}</pre><pre>func (d duck) walk() {<br>d.w.walk()<br>}</pre><pre>func (d duck) swim() {<br>d.s.swim()<br>}</pre><pre>func (alive) eat() {<br>fmt.Println(&quot;Alive and eating&quot;)<br>}</pre><pre>func (alive) sleep() {<br>fmt.Println(&quot;Alive and sleeping&quot;)<br>}</pre><pre>func (walkable) walk() {<br>fmt.Println(&quot;strolling through&quot;)<br>}</pre><pre>func (swimable) swim() {<br>fmt.Println(&quot;Taking a dip&quot;)<br>}</pre><pre>func main() {<br>d := duck{}<br>d.eat()<br>d.sleep()<br>d.walk()<br>d.swim()<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*So-Y7tuW9W8hfNPDJ4o5vw.png" /></figure><p>So, this was all about composition in Go.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0eff45c2df3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[(Go)ing Generic: Writing type-free functions in Go]]></title>
            <link>https://medium.com/codex/go-ing-generic-writing-type-free-functions-in-go-40c736c422e5?source=rss-7ff7983dc83e------2</link>
            <guid isPermaLink="false">https://medium.com/p/40c736c422e5</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[generics-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Shayan khan]]></dc:creator>
            <pubDate>Sat, 29 Oct 2022 19:13:29 GMT</pubDate>
            <atom:updated>2022-11-03T16:45:13.722Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are familiar with C++, you probably have heard about templates. Templates. The simple idea behind templates is that to pass the data type as parameter so that we do not have to write the same code for different data types. Same is the case with generics in Golang which are expressed as the following three types:</p><p><strong>Type Parameter:</strong></p><p>First of all, let’s write a simple function which takes two integers as parameters and returns the minimum of the two numbers:</p><pre>package main</pre><pre>import &quot;fmt&quot;</pre><pre>func main() {<br>fmt.Println(min(1, 2))<br>}</pre><pre>func min(a int, b int) int {<br>if a &lt; b {<br>return a<br>}<br>return b<br>}</pre><p>This function returns 1 which is the minimum value :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WOuJC1Kscy9mppugpv0BQQ.png" /></figure><p>But if we pass 1.1 as one of the values to this functions, it will give us a compile time error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6llvjMXS4J5f588ZSG90Ag.png" /></figure><p>This is because the function expected to receive an int and not a float. How do we solve this problem? This is where type parameters kick in:</p><p>For this, we will be using a separate function for the time being and will return to the minimum function later on:</p><pre>func returnNum[T any](a T, b T) T {<br>return b<br>}</pre><p>Which can be called like:</p><pre>func main() {<br>fmt.Println(returnNum[int32](1, 2))<br>}</pre><p>This function returns any type that is given to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nE8tduNFQgwzuf-WJzQ47Q.png" /></figure><p>So, this how type parameters allow us to pass any type to functions in Go.</p><p>Second type we need to talk about is:</p><p><strong>Type Inference:</strong></p><p>This basically deals with the underlying types, for example in the following piece of code we have declared a new type fakeInt32 which basically int32, but our function would not accept fakeInt32 as it is not exactly int32:</p><pre>func main() {<br>type fakeInt32 int32<br>var number fakeInt32 = 23<br>fmt.Println(returnNum[int32](number, 2))<br>}</pre><pre>func returnNum[T int32](a T, b T) T {<br>return b<br>}</pre><p>But this gives us a compile time error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g9mkzDnWS_4dyotS6yEzxQ.png" /></figure><p>So, type inference helps us to deal with this, all we have to add a “~” operator in front of the expected type, this would make sure all the types which have int32 as the underlying type are also accepted as well.</p><pre>func returnNum[T ~int32](a T, b T) T {<br>return b<br>}</pre><p>So,the output now would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MC3lhiwTOfpitvholF6xSQ.png" /></figure><p>Which is the expected output.</p><p>Now, turning our attention towards:</p><p><strong>Type Set:</strong></p><p>Let’s get back to the min function:</p><pre>func min[T any](a T, b T) T {<br>if a &lt; b {<br>return a<br>}<br>return b<br>}</pre><p>This would give a compile time error as the &lt; operator is not defined for all the types:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*03ikk0FVMceQYnAUXVKdKg.png" /></figure><p>Type set can help us with this, we can define a type set like this:</p><pre>type typeSet interface {<br>~int32 | float32<br>}</pre><p>So, this defines a type set which involves types which supports the &lt; operator, the function would look like this:</p><pre>func min[T typeSet](a T, b T) T {<br>if a &lt; b {<br>return a<br>}<br>return b<br>}</pre><p>And it gives the expected output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*617EibCIpcHuMZY0dXlrUQ.png" /></figure><p>So, this was all about generics in Go.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40c736c422e5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/go-ing-generic-writing-type-free-functions-in-go-40c736c422e5">(Go)ing Generic: Writing type-free functions in Go</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Testing : Using go-cmp to compare equality]]></title>
            <link>https://medium.com/@shayannoor123khan/go-testing-using-go-cmp-to-compare-equality-2f3e4b8334fe?source=rss-7ff7983dc83e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f3e4b8334fe</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Shayan khan]]></dc:creator>
            <pubDate>Sun, 23 Oct 2022 13:25:49 GMT</pubDate>
            <atom:updated>2022-10-23T13:25:49.455Z</atom:updated>
            <content:encoded><![CDATA[<h3>Go Testing : Using go-cmp to compare equality</h3><p>As we know, Testing is all about checking if a certain piece of code gives the desired output or not. Testing is Go is used for the following purposes :</p><ul><li>Coverage</li><li>Benchmarking</li><li>Parallelism</li><li>Teardown</li></ul><p>Testing is possible in go in the following ways :</p><p><strong>(a) Vanilla Comparision:</strong></p><p><strong>Included in Go :</strong></p><ul><li>== and !=</li><li>reflect.DeepEqual</li><li>github.com/google/go-cmp</li></ul><p><strong>(b) Assertion Packages</strong></p><p>Mostly, equality operators provided by Go check if the two values given are actually equal or not , where as gocmp provides helps us identify if two values/structures provided are semantically equal or not. Semantic equality is when data provided by two different entities has the same meaning.</p><p>Let’s start by testing go functions in the conventional way which is by using the equal operator. Let us take a simple function :</p><pre>func SumSimple(a, b int) int {<br>return a + b<br>}</pre><p>This function returns sum of two numbers. It can be tested like this:</p><pre>func TestSumSimple(t *testing.T) {</pre><pre>t.Parallel()</pre><pre>type input struct {<br>a int<br>b int<br>}</pre><pre>tests := []struct {<br>name     string<br>input    input<br>expected int<br>}{<br>{<br>&quot;OK: 1+2&quot;,<br>input{1, 2},<br>4,<br>},<br>{<br>&quot;OK: 2-2&quot;,<br>input{2, -2},<br>0,<br>},<br>}</pre><pre>for _, test := range tests {<br>test := test<br>t.Run(test.name, func(t *testing.T) {<br>t.Parallel()<br>if actual := operation.SumSimple(test.input.a, test.input.b); actual != test.expected {<br>t.Fatalf(&quot;expected %d, actual %d&quot;, test.expected, actual)<br>}<br>})<br>}<br>}</pre><p>This function is one way we can test if the values are equal but as you can see we have to loop through each and every value to check if its equal or not, this check if the values are absolutely equal and the test will fail even if the values are sematically equal.</p><p>So for this purpose, gocmp is used. Now, to show the difference of how we can use gocmp to check values are semantically equal or not we are defining are concatenation function which concatenates two slices.</p><pre>func ConcatenateSlice(a, b []int) []int {<br>res := make([]int, len(a), len(a)+len(b))<br>_ = copy(res, a)<br>res = append(res, b...)<br>return res<br>}</pre><p>Now, there are two ways to test this, one is to test the equality other is to test semantically.First, let’s define a function that would check if the slices are exactly equal or not :</p><pre>func TestConcatenateSlice_Equally(t *testing.T) {<br>t.Parallel()</pre><pre>type (<br>input struct {<br>a []int<br>b []int<br>}<br>)</pre><pre>tests := []struct {<br>name     string<br>input    input<br>expected []int<br>}{<br>{<br>&quot;OK&quot;,<br>input{<br>[]int{1, 2},<br>[]int{-1, -2},<br>},<br>[]int{1, 2, -1, -2},<br>},<br>}</pre><pre>for _, test := range tests {<br>test := test<br>t.Run(test.name, func(t *testing.T) {<br>t.Parallel()<br>actual := operation.ConcatenateSlice(test.input.a, test.input.b)<br>if len(actual) != len(test.expected) {<br>t.Fatalf(&quot;result lenghts are different: expected %d, actual %d&quot;, len(test.expected), len(actual))<br>}</pre><pre>for i, v := range actual {<br>if v != test.expected[i] {<br>t.Fatalf(&quot;values at %d index are different: expected %d, actual %d&quot;, i, test.expected[i], v)<br>}<br>}<br>})<br>}<br>}</pre><p>So, if the input is [1,2] and [-1,-2] the output will be ok which is “exactly equal” to [1,2,-1,-2] :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yirnXp_dcjPzLIqyw7-uWA.png" /></figure><p>And if the inputs are [1,-2] and [-1.2], it returns fail as the values are not exactly equal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TOtz6Zq3wdcdKaJInsdlg.png" /></figure><p>So, this function only checks if the values are exactly equal or not, so we have to define another function for semantic equality.</p><pre>func TestCmp_SlicesSematicallySorting(t *testing.T) {<br>t.Parallel()</pre><pre>tests := []struct {<br>name   string<br>input  []int<br>output []int<br>}{<br>{&quot;OK&quot;,<br>[]int{1, 2, 3},<br>[]int{2, 1, 3}<br>},<br>}</pre><pre>for _, test := range tests {<br>test := testt.Run(test.name, func(t *testing.T) {<br>t.Parallel()<br>opt := cmpopts.SortSlices(func(a, b int) bool {<br>return a &lt; b<br>})</pre><pre>if !cmp.Equal(test.input, test.output, opt) {<br>t.Fatalf(&quot;values are not the same %s&quot;, cmp.Diff(test.input, test.output, opt))<br>}<br>})<br>}<br>}</pre><p>When the function is tested in this way, it checks if the values are semantically equal or not. Be it [1,2],[-1,-2] or [1,-2],[-1,2] the output will always be :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sP2Ey6bmCJySmORgO4Gezw.png" /></figure><p>So, this how gocmp helps us test whether the values are semantically equal or not.</p><p><strong>For reference :</strong></p><p>operation “github.com/MarioCarrion/videos/2021/01/23-go-package-equality-google-go-cmp”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f3e4b8334fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Channels : Enabling communication between routines in Go]]></title>
            <link>https://medium.com/@shayannoor123khan/channels-enabling-communication-between-routines-in-go-f48afad6f1ac?source=rss-7ff7983dc83e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f48afad6f1ac</guid>
            <category><![CDATA[channel]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Shayan khan]]></dc:creator>
            <pubDate>Tue, 18 Oct 2022 20:59:22 GMT</pubDate>
            <atom:updated>2022-10-18T20:59:22.813Z</atom:updated>
            <content:encoded><![CDATA[<h3>Channels : Enabling communication between routines in Go</h3><p>In Go, we can communicate between routines by using channels. Taking the following piece of code as an example:</p><pre>package main<br></pre><pre>import (</pre><pre>&quot;fmt&quot;</pre><pre>&quot;net/http&quot;</pre><pre>)<br></pre><pre>func main() {</pre><pre>websites := []string{</pre><pre>&quot;http://google.com&quot;,</pre><pre>&quot;http://facebook.com&quot;,</pre><pre>&quot;http://golang.org&quot;,</pre><pre>}<br></pre><pre>for _, website := range websites {</pre><pre>go checkwebsite(website)</pre><pre>}</pre><pre>}<br></pre><pre>func checkwebsite(website string) {</pre><pre>_, err := http.Get(website)</pre><pre>if err != nil {</pre><pre>fmt.Println(website, &quot;might be down!&quot;)</pre><pre>return</pre><pre>}</pre><pre>fmt.Println(website, &quot;is up!&quot;)</pre><pre>}</pre><p>The function “checkwebsite” has been launched as a separate routine from the main routine which is launched once we execute our program. So, essentially everytime we run the function using the “go” keyword it is run on a separate thread as compared to the main thread. So, the output should be as expected but…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gEjLL6NK4z40CFuntyC1ig.png" /></figure><p>Why is that so ? This is because once the main thread has completed its work it does not wait for the other routines to come back and it just exits as it is the only routine which the exit rights. So, there must be some way to notify the main routine if the child routines have finished executing or not, this can be obtained using channels in Golang. We are required to follow some rules while creating channels :</p><p>(i) Channels are typed, which means the information we intend to share between different routines must be of the same type.</p><p>(ii) Channels are always two way communicating. You can both send and receive information using channels.</p><p>Now, let’s begin by adding channels to the code above :</p><pre>package main</pre><pre>import (</pre><pre>&quot;fmt&quot;</pre><pre>&quot;net/http&quot;</pre><pre>)</pre><pre>func main() {</pre><pre>websites := []string{</pre><pre>&quot;http://google.com&quot;,</pre><pre>&quot;http://facebook.com&quot;,</pre><pre>&quot;http://golang.org&quot;,</pre><pre>}</pre><pre>c := make(chan string)</pre><pre>for _, website := range websites {</pre><pre>go checkwebsite(website, c)</pre><pre>}</pre><pre>fmt.Println(&lt;-c)</pre><pre>}</pre><pre>func checkwebsite(website string, c chan string) {</pre><pre>_, err := http.Get(website)</pre><pre>if err != nil {</pre><pre>fmt.Println(website, &quot;might be down!&quot;)</pre><pre>c &lt;- &quot;Is down&quot;</pre><pre>return</pre><pre>}</pre><pre>fmt.Println(website, &quot;is up!&quot;)</pre><pre>c &lt;- &quot;is up&quot;</pre><pre>}</pre><p>Notice how channels have been added as an argument to the “checkwebsite” function with the name “c”. The value is fed into the channel inside the function while it’s received in the main function. It gives the below output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cSwjQneBW8cJI4Ljs04Vqg.png" /></figure><p>Which again is not the intended output as the website check for only one link completed till program completion. This happens because the blocking call in our main routine is fmt.Println(&lt;-c) which is essentially waiting for the channel to receive a value, once it receives the first value, it passes the blocking condition and exits the program. This problem can be solved in the following way :</p><p>One way to solve is to write as many blockers in the main routine as the number of values you expect the channel to receive.</p><pre>package main</pre><pre>import (</pre><pre>&quot;fmt&quot;</pre><pre>&quot;net/http&quot;</pre><pre>)</pre><pre>func main() {</pre><pre>websites := []string{</pre><pre>&quot;http://google.com&quot;,</pre><pre>&quot;http://facebook.com&quot;,</pre><pre>&quot;http://golang.org&quot;,</pre><pre>}</pre><pre>c := make(chan string)</pre><pre>for _, website := range websites {</pre><pre>go checkwebsite(website, c)</pre><pre>}</pre><pre>fmt.Println(&lt;-c)<br>fmt.Println(&lt;-c)<br>fmt.Println(&lt;-c)</pre><pre>}</pre><pre>func checkwebsite(website string, c chan string) {</pre><pre>_, err := http.Get(website)</pre><pre>if err != nil {</pre><pre>fmt.Println(website, &quot;might be down!&quot;)</pre><pre>c &lt;- &quot;Is down&quot;</pre><pre>return</pre><pre>}</pre><pre>fmt.Println(website, &quot;is up!&quot;)</pre><pre>c &lt;- &quot;is up&quot;</pre><pre>}</pre><p>But this would not be a dynamic approach. To make it dynamic, we can do the following code alterations :</p><pre>package main</pre><pre>import (</pre><pre>&quot;fmt&quot;</pre><pre>&quot;net/http&quot;</pre><pre>)</pre><pre>func main() {</pre><pre>websites := []string{</pre><pre>&quot;http://google.com&quot;,</pre><pre>&quot;http://facebook.com&quot;,</pre><pre>&quot;http://golang.org&quot;,</pre><pre>}</pre><pre>c := make(chan string)</pre><pre>for _, website := range websites {</pre><pre>go checkwebsite(website, c)</pre><pre>}</pre><pre>for i := 0 ; i &lt; len(websites) ; i++ {</pre><pre>fmt.Println(&lt;-c)</pre><pre>}</pre><pre>func checkwebsite(website string, c chan string) {</pre><pre>_, err := http.Get(website)</pre><pre>if err != nil {</pre><pre>fmt.Println(website, &quot;might be down!&quot;)</pre><pre>c &lt;- &quot;Is down&quot;</pre><pre>return</pre><pre>}</pre><pre>fmt.Println(website, &quot;is up!&quot;)</pre><pre>c &lt;- &quot;is up&quot;</pre><pre>}</pre><p>This makes our approach dynamic making it scalable to any size of input. However, both the approaches give the same output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K_R6Vfavm01NgtPF0LaPAQ.png" /></figure><p>Which is the intended output. So that was all related to channels in Go. Keep Learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f48afad6f1ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go : Memory Management]]></title>
            <link>https://medium.com/@shayannoor123khan/go-memory-management-fa6f9ebf9e8c?source=rss-7ff7983dc83e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa6f9ebf9e8c</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[memory-management]]></category>
            <dc:creator><![CDATA[Shayan khan]]></dc:creator>
            <pubDate>Mon, 10 Oct 2022 20:18:20 GMT</pubDate>
            <atom:updated>2022-10-10T20:18:20.329Z</atom:updated>
            <content:encoded><![CDATA[<h3>Go : Memory Management</h3><p>Whenever a programmer starts to learn or practice a new language, the first question that arises to his/her mind is that how memory is managed in that particular language. In this case, we learn how memory is managed in Golang.</p><p>First things first, memory allocation and deallocation happens automatically in Go.</p><p>For memory management in Go, two common methods are used :</p><p><strong>new()</strong> : This method allocates memory but does not initialize it, and in turn it returns a memory address but it is zeroed storage which means writing zeroes to the whole storage.</p><p><strong>make() : </strong>This method allocates memory as well as it initializes it, and in turn it returns a memory address but it is non zeroed storage which means the entire storage is not written with zero.</p><p>Another aspect which is important with regards to memory management is that garbage collection.</p><p><strong>Garbage Collection : </strong>Garbage collection happens automatically in Go, when Go was initially developed it’s garbage collector was talked about a lot due to its low efficiency, but at the later stage it was rewritten completely to provide more efficiency.</p><p>So, this is how memory is managed in Go.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa6f9ebf9e8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[(Go)ing Atomic : Controlling state by using atomic variables in Go]]></title>
            <link>https://medium.com/@shayannoor123khan/go-ing-atomic-controlling-state-by-using-atomic-variables-in-go-2d61ea4dbb13?source=rss-7ff7983dc83e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d61ea4dbb13</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[atomicity]]></category>
            <category><![CDATA[condition-variable]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Shayan khan]]></dc:creator>
            <pubDate>Thu, 29 Sep 2022 19:38:36 GMT</pubDate>
            <atom:updated>2022-09-29T19:38:36.813Z</atom:updated>
            <content:encoded><![CDATA[<h3>(Go)ing Atomic : Controlling state by using atomic variables in Go</h3><p>A race condition is such when two coroutines access the shared variable at the same time, both coroutines read the same value of the shared variable, and then perform their operations on it and then “race” to see which coroutine can write the value last to the variable overwriting the value written by the previous coroutine. Such conditions can be avoided by using “Atomic variables” in Go.</p><p>In Simpler terms, Atomicity is used in Golang to control state. Let’s understand this by the reference of an example :</p><pre>package main<br></pre><pre>import (</pre><pre>&quot;fmt&quot;</pre><pre>&quot;sync&quot;</pre><pre>)<br></pre><pre>func main() {</pre><pre>var iteration uint64</pre><pre>var waitgroup sync.WaitGroup</pre><pre>for i := 0; i &lt; 1000; i++ {</pre><pre>waitgroup.Add(1)</pre><pre>go func() {</pre><pre>iteration++</pre><pre>waitgroup.Done()</pre><pre>}()</pre><pre>}</pre><pre>waitgroup.Wait()</pre><pre>fmt.Println(&quot;Counter:&quot;, iteration)</pre><pre>}</pre><p>The following piece of code will give the following output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*izTNxIxZ-a_UYzoEqh8ApQ.png" /></figure><p>As you can see, it will never give the output “1000” which is supposed to produce. This is because the variable iteration is being accessed by more than one coroutine at the same time, for instance, coroutine 1 comes and reads the value of iteration as 1 and coroutine 2 reads the same value as well , both coroutines perform their operations on the same written value , and both return the value 2 which means one of the coroutine iteration is useless i.e. both coroutines incremented the value of iteration ( that was 1 ) to 2 , had it been used in an atomic way one coroutine would have made it 2 and the other would have increased it to 3.</p><p>Now, let’s make some changes to the code to make it work in an atomic way…</p><pre>package main<br></pre><pre>import (</pre><pre>&quot;fmt&quot;</pre><pre>&quot;sync&quot;</pre><pre>&quot;sync/atomic&quot;</pre><pre>)<br></pre><pre>func main() {</pre><pre>var iteration uint64</pre><pre>var waitgroup sync.WaitGroup</pre><pre>for i := 0; i &lt; 1000; i++ {</pre><pre>waitgroup.Add(1)</pre><pre>go func() {</pre><pre>//iteration++</pre><pre>atomic.AddUint64(&amp;iteration, 1)</pre><pre>waitgroup.Done()</pre><pre>}()</pre><pre>}</pre><pre>waitgroup.Wait()</pre><pre>fmt.Println(&quot;Counter:&quot;, iteration)</pre><pre>}</pre><p>This code will give the following output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jgk_8fDhMdR3FqYRdoT-YA.png" /></figure><p>As, you can see adding the atomic keyword(obtained from sync/atomic) makes the program give the intended output. This is because adding the atomic keyword allows only one coroutine to access the shared variable at a time , which ensures there are no race conditions and every coroutine performs the operation in the correct manner.</p><p>So, to avoid race conditions, one must look into how atomicity can be used for controlling state.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d61ea4dbb13" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>