<?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 Nikhil Vaidyar on Medium]]></title>
        <description><![CDATA[Stories by Nikhil Vaidyar on Medium]]></description>
        <link>https://medium.com/@nikhilvaidyar?source=rss-d2d76b301ce------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aIfFXh2oUpY3fDfZ30DKUg.jpeg</url>
            <title>Stories by Nikhil Vaidyar on Medium</title>
            <link>https://medium.com/@nikhilvaidyar?source=rss-d2d76b301ce------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:36:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nikhilvaidyar/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[Getting Started with Kyverno: A Beginner’s Guide to Policy Creation and Implementation]]></title>
            <link>https://levelup.gitconnected.com/getting-started-with-kyverno-a-beginners-guide-to-policy-creation-and-implementation-6a660f1d7334?source=rss-d2d76b301ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a660f1d7334</guid>
            <category><![CDATA[concepts-for-beginners]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kyverno]]></category>
            <category><![CDATA[cncf]]></category>
            <category><![CDATA[sre]]></category>
            <dc:creator><![CDATA[Nikhil Vaidyar]]></dc:creator>
            <pubDate>Fri, 27 Sep 2024 17:38:29 GMT</pubDate>
            <atom:updated>2024-09-29T14:21:30.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ETMu2QHI-l4p-_QJ" /><figcaption><em>Photo by</em><a href="https://unsplash.com/@sakiii999?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash"><em> Saketh</em></a><em> on</em><a href="https://unsplash.com/photos/gray-and-black-control-panel-P4w7ErpthZ4?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash"><em> Unsplash</em></a></figcaption></figure><p>In this overview, I will explain what Kyverno is, how it works, and why we need it besides why we need policies to support Kubernetes resources. While delving into this awesome CNCF project. Let’s first get familiar with some real-world explanations. There’s an image above of a sound mixer which helps to blend and balance various audio inputs to create a clear, harmonious output. Just like that Kyverno also orchestrates and manages various policies for Kubernetes resources to maintain a secure, compliant and consistent environment.</p><p>In the sound mixer, we have equalizers which generally adjust sound frequencies to achieve sound clarity, similarly in Kyverno we can follow the <strong>validation</strong> policy for the resource like having resource limits in pods to avoid performance and CPU scarcity issues. We also have a filters/effects option in the sound mixer with which we can modify the audio signals using reverb to improve the audio signal, similarly in Kyverno we have a <strong>mutation</strong> policy for the resource which adds/modifies the resources to ensure consistency. Suppose, a pod doesn’t have a label this policy will automatically add it just like how effects automatically transform the audio signal. Last but not least, some sound mixers also have automation or auto-routing which helps to route the different audio inputs to a specific output, similarly, in Kyverno we have a <strong>generation</strong> policy in which resources get generated based on events, more like auto-tuning sound in the sound mixer.</p><h3>What is Kyverno and how does it work?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xt63cNvv2M5tivtp" /><figcaption><em>Photo by</em><a href="https://unsplash.com/@hojipago?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash"><em> EJ Yao</em></a><em> on</em><a href="https://unsplash.com/photos/several-cranes-above-the-buildings-D46mXLsQRJw?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash"><em> Unsplash</em></a></figcaption></figure><p>Kyverno is an open-source Kubernetes policy engine designed to help manage, automate, generate and validate configuration with the Kubernetes cluster. Kyverno is particularly useful for compliance, security and maintaining consistency in Kubernetes environments.</p><p><strong>Features of Kyverno:</strong></p><ul><li>It uses policies such as Kubernetes resources</li><li>It synchronizes the configurations across namespaces</li><li>Manages policies as code using tools like git and kustomize.</li><li>It also matches resources using labels.</li><li>It validates, generates, and mutates any resource.</li></ul><h3>Kyverno — Behind the scenes</h3><p>We know that Kyverno is a Kubernetes policy engine that operates within a Kubernetes cluster to validate, manage, mutate and generate configurations based on the policies defined. It uses webhooks or say it runs as a dynamic admission controller in a K8s cluster. It integrates directly with the Kubernetes API and works as an admission controller, intercepting requests to create or update resources and ensuring they comply with policies before being accepted into the cluster.</p><p>Here’s the high-level architecture of Kyverno</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AYlTpFg4A8Swj__D" /><figcaption><em>High-level architecture from the official </em><a href="https://kyverno.io/docs/introduction/"><em>Kyverno</em></a><em> website</em></figcaption></figure><p>Let’s deduce this diagram in a simpler way to understand how Kyverno controllers or policies get integrated with Kubernetes clusters.</p><ul><li>The <strong>Webhook</strong> is a server that processes requests from the Kubernetes API.</li><li>Then, It takes these requests and sends them to Kyverno’s <strong>Engine</strong> for policy checks.</li><li>The Webhook’s behaviour is managed by the <strong>Webhook Controller</strong>, which watches the policies in the cluster and adjusts the Webhook to only process resources that match those policies.</li><li>There’s also a <strong>Cert Renewer</strong> that automatically renews certificates stored as Kubernetes Secrets, which are required by the Webhook to work properly.</li><li>The <strong>Background Controller</strong> handles policies that generate or update resources by processing <strong>UpdateRequests</strong>, which are special resources created to manage these changes.</li><li>The <strong>Report Controllers</strong> create and update <strong>Policy Reports</strong> based on <strong>Admission Reports</strong> (from new resources) and <strong>Background Scan Reports</strong> (for existing resources).</li></ul><p>Kyverno also supports <strong>high availability</strong>. This means you can set it up with multiple replicas of certain controllers to make sure it keeps running smoothly, even if one instance fails. More replicas can also help Kyverno handle more workload, making it more scalable. You can check the high availability section for details on how this works for each Kyverno controller and its components.</p><h3>Why do we need Kyverno?</h3><p>We need Kyverno because it simplifies managing security, compliance and configuration policies in Kubernetes environments. It fills the gaps by providing an easy way to integrate K8s clusters using this policy management tool.</p><ul><li>It enforces the Kubernetes Resource Standards.</li><li>It ensures security, compliance and consistency.</li><li>Automatically generates custom policies.</li><li>To monitor compliances it provides valuable insights via audit and reporting tools.</li><li>It’s a native Kubernetes integration that seamlessly works with Kubernetes API and the resource model.</li></ul><h3>How do we create policies and implement them?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EUq-cLjMa7R6qcpW" /><figcaption><em>Photo by</em><a href="https://unsplash.com/@aleexcif?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash"><em> Soliman Cifuentes</em></a><em> on</em><a href="https://unsplash.com/photos/the-sun-shines-through-the-leaves-of-a-palm-tree-YMmq-CzBQs0?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash"><em> Unsplash</em></a></figcaption></figure><p>Implementing and creating policies in Kyverno is mostly straightforward as it’s integrated seamlessly with Kubernetes. As we write declarative manifest for K8s using YAML, we need to write the policies using YAML. We can use Kyverno policies to validate, mutate, manage or generate Kubernetes resources automatically.</p><h3>Types of Policies and their implementations</h3><h4>Validation Policy</h4><p>It ensures that resources meet the specific criteria provided in the policy to validate Kubernetes resources. It is the most common use case for policy and decision-making process and later it generates the policy report whether it is passed or failed.</p><p>Here’s one example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fDcJk6iB5ehEXdWV" /></figure><p>Check out this live link for Kyverno playground to access the validation policy example: <a href="https://tinyurl.com/4d3h7yhj">https://tinyurl.com/4d3h7yhj</a></p><p><em>Note: In the above example, I am validating the resource and also clicking on start to review the policy report.</em></p><p><strong>Rule Name</strong>: check-app-label<br><strong>Target Resource</strong>: Pods<br><strong>Validation Action</strong>: Check if all Pods have an app label.</p><h4>Mutation Policy</h4><p>It modifies resources automatically to ensure compliance and automatically adds the configuration to the Kubernetes resources. Also, a mutate rule is similar to a validate rule it selects some that of resources and defines the desired state.</p><p>Here’s one example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Id2C5hrTVd1WhUVl" /></figure><p>In this example, you can see <strong><em>patchStrategicMerge </em></strong>which is useful when a specific mutation is needed and it merges the changes automatically to the resources like Pods, ConfigMaps, etc.</p><p>Check out this live link for Kyverno playground to access the mutation policy example: <a href="https://tinyurl.com/32mw7des">https://tinyurl.com/32mw7des</a></p><p><em>Note: In the above example, I am using the mutation policy which automatically updates the resource labels. For more click, on the start and then the details section of the policy report.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LOyJPW5ofYhID0Ow" /></figure><p><strong>Rule Name</strong>: add-default-label<br><strong>Target Resource</strong>: Pod<br><strong>Mutation Action</strong>: Automatically add the app: default-app label to all Pods</p><h4>Generation Policy</h4><p>This policy generates a default ConfigMap whenever a new namespace is created.</p><p>Here’s one example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zkywUe-N-BFawbi3" /></figure><p>Check out this live link for Kyverno playground to access the validation policy example: <a href="https://tinyurl.com/bdfeyh8f">https://tinyurl.com/bdfeyh8f</a></p><blockquote><em>Note: In the above example, I am using the generation policy which creates the ConfigMap to any new Namespace. For more click, on the start and then the details section of the policy report.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xeuYco1M7da5Zx6L" /></figure><p><strong>Rule Name</strong>: generate-configmap<br><strong>Target Resource</strong>: Namespace<br><strong>Generation Action</strong>: It automatically creates a ConfigMap resource in any new Namespace with key-value pair <strong><em>key: default-value</em></strong></p><p>These are the types of policies with which you can manage your Kubernetes resources.</p><blockquote>Here’s the command to install the Kyverno in your system:<br>kubectl apply -f <a href="https://github.com/kyverno/kyverno/releases/download/v1.9.0/install.yaml">https://github.com/kyverno/kyverno/releases/download/v1.9.0/install.yaml</a></blockquote><h3>References:</h3><ul><li><a href="https://kyverno.io/docs/introduction/">https://kyverno.io/docs/introduction/</a></li><li><a href="https://kyverno.io/docs/kyverno-policies/">https://kyverno.io/docs/kyverno-policies/</a></li><li><a href="https://devtron.ai/blog/how-to-secure-kubernetes-clusters-with-kyverno-policies/">https://devtron.ai/blog/how-to-secure-kubernetes-clusters-with-kyverno-policies/</a></li><li><a href="https://tech.groww.in/kyverno-a-kubernetes-native-policy-management-bdd5bc80b8ca">https://tech.groww.in/kyverno-a-kubernetes-native-policy-management-bdd5bc80b8ca</a></li><li><a href="https://medium.com/techloop/understanding-kyverno-policies-7e2d8651d7b1">https://medium.com/techloop/understanding-kyverno-policies-7e2d8651d7b1</a></li></ul><p>I hope you like this brief introduction to Kyverno — an awesome policy management tool that helps create custom policies and we can do much more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a660f1d7334" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/getting-started-with-kyverno-a-beginners-guide-to-policy-creation-and-implementation-6a660f1d7334">Getting Started with Kyverno: A Beginner’s Guide to Policy Creation and Implementation</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data structures implementation in Golang]]></title>
            <link>https://levelup.gitconnected.com/data-structures-implementation-in-golang-20b652305934?source=rss-d2d76b301ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/20b652305934</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[concept]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Nikhil Vaidyar]]></dc:creator>
            <pubDate>Wed, 01 Mar 2023 21:45:48 GMT</pubDate>
            <atom:updated>2023-03-07T19:11:19.598Z</atom:updated>
            <content:encoded><![CDATA[<p>As software engineers, we need to implement optimal data structures to solve our day-to-day tasks like we need to use arrays, linked lists, hashmaps, etc. In this blog, I will try to cover all the use cases and implementation with each data structure.</p><blockquote>Note: This blog is lengthy as I thought to explain all data structures in one go. As reader could just easily scroll rather than opening multiple urls. Meanwhile, I have segregatted each data structure, the way it should be aligned. The purpose of creating this blog is to simply get familiar with data structures using golang and also this kind of questions most of the time comes in interview rounds, so yeah it would be a good practice, if you get through this blog till the end. <br><strong>Hence</strong>: It’s a journal for all the data structures in Golang.</blockquote><h3>Arrays/Slices</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XewPbghS551jfIVR" /><figcaption>Photo by <a href="https://unsplash.com/@pawel_czerwinski?utm_source=medium&amp;utm_medium=referral">Pawel Czerwinski</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s start with arrays as this is the data structure that we use very often to store our data and we can perform data transformation, manipulation, etc. Arrays are like collections of elements; for more, you can check them out on <a href="https://en.wikipedia.org/wiki/Array_(data_structure)"><em>Wikipedia</em></a>. For more insights into <strong>arrays</strong>, do check out my blog on <a href="https://medium.com/@nikhilvaidyar/golang-basics-array-and-slices-9652dfd271dc"><strong><em>Arrays and Slices</em></strong></a>. Let’s take an example with crud operations:</p><pre>//To checkout this example on playground and to get more insights, <br>//click on this link: https://go.dev/play/p/LtJ4rUfu5Oi<br><br>//Arrays implementation<br>package main<br><br>import &quot;fmt&quot;<br><br>/* <br> * Description: Initializing or array creation<br> * @Output - array of integers<br> * TC - O(1) | SC - O(1)<br>*/<br>func createArray() []int {<br> arr := []int{1, 2, 3, 4, 5, 6, 7}<br> fmt.Printf(&quot;Array created: %d\n&quot;, arr)<br> return arr<br>}<br><br>/* <br> * Description: Reading elements in array<br> * @Input - array of integers<br> * TC - O(n) | SC - O(1)<br>*/<br>func readArray(arr []int) {<br> for i := 0; i &lt; len(arr); i++ {<br>  fmt.Printf(&quot;Reading each array element: %d\n&quot;, arr[i])<br> }<br>}<br><br>/* <br> * Description: Updating elements in array<br> * @Input - array of integers<br> * TC - O(1) | SC - O(1)<br> * Note: If we are appending on range/for loop, <br> * then space complexity becomes O(N)<br>*/<br>func updateArray(arr []int) {<br> arr[2] = 890<br> fmt.Printf(&quot;Updating by array index - arr[2]: %d\n&quot;, arr[2])<br><br> arr1 := []int{99, 100}<br> arr = append(arr, arr1...)<br> fmt.Printf(&quot;Updating by appending a new array to current array: %d\n&quot;, arr)<br>}<br><br>/* <br> * Description: Deleting an array<br> * @Input - array of integers<br> * @Output - array of integers<br> * TC - O(1) | SC - O(1)<br>*/<br>func deleteArray(arr []int) []int {<br> arr = []int{}<br> fmt.Printf(&quot;Array is deleted from the memory: %d\n&quot;, arr)<br> return arr<br>}<br><br>/* <br> * Description: Deleting an elements by index in an array<br>   * Basically, we are reslicing after removing an element by index<br>   * To achieve the correct form of elements in an array, we need to<br>   * reslice the elements before the index and with the appending slice<br>   * we need to return all the resliced elements after the index in an array<br>   * for all this we need to append to the same array, thus this will do this<br>   * all by callbyreference to update the original array<br> * @Input - slice -&gt; array of integers, index -&gt; integer<br> * @Output - array of integers<br> * TC - O(1) | SC - O(1)<br>*/<br>func removeElemByIndex(slice []int, index int) []int {<br> return append(slice[:index], slice[index+1:]...)<br>}<br><br>func main() {<br> arr := createArray()<br> index := 2<br> fmt.Println(&quot;---------------------------------------------------------------------------&quot;)<br> readArray(arr)<br> fmt.Println(&quot;---------------------------------------------------------------------------&quot;)<br> updateArray(arr)<br> fmt.Println(&quot;---------------------------------------------------------------------------&quot;)<br> readArray(arr)<br> fmt.Println(&quot;---------------------------------------------------------------------------&quot;)<br> arr = deleteArray(arr)<br> fmt.Println(&quot;---------------------------------------------------------------------------&quot;)<br> arr = createArray()<br> fmt.Println(&quot;---------------------------------------------------------------------------&quot;)<br> fmt.Printf(&quot;After removing index %d from array %d\n&quot;, index, removeElemByIndex(arr, index))<br> fmt.Println(&quot;---------------------------------------------------------------------------&quot;)<br> readArray(arr)<br>}<br><br>Output from the above code:<br>Array created: [1 2 3 4 5 6 7]<br>---------------------------------------------------------------------------<br>Reading each array element: 1<br>Reading each array element: 2<br>Reading each array element: 3<br>Reading each array element: 4<br>Reading each array element: 5<br>Reading each array element: 6<br>Reading each array element: 7<br>---------------------------------------------------------------------------<br>Updating by array index - arr[2]: 890<br>Updating by appending a new array to current array: [1 2 890 4 5 6 7 99 100]<br>---------------------------------------------------------------------------<br>Reading each array element: 1<br>Reading each array element: 2<br>Reading each array element: 890<br>Reading each array element: 4<br>Reading each array element: 5<br>Reading each array element: 6<br>Reading each array element: 7<br>---------------------------------------------------------------------------<br>Array is deleted from the memory: []<br>---------------------------------------------------------------------------<br>Array created: [1 2 3 4 5 6 7]<br>---------------------------------------------------------------------------<br>After removing index 2 from array [1 2 4 5 6 7]<br>---------------------------------------------------------------------------<br>Reading each array element: 1<br>Reading each array element: 2<br>Reading each array element: 4<br>Reading each array element: 5<br>Reading each array element: 6<br>Reading each array element: 7<br>Reading each array element: 7</pre><h4>When do we need to use arrays?</h4><p>We need to use arrays when we need to store small amounts of data or we can say data that is fixed in size. If memory is limited, an array would be a good option. As arrays, store data in a contiguous manner so, if we are very particular about the storage of data in a sequential/contiguous manner, it’s good to array there as well.</p><h3>LinkedList</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B-6cbv00gwWFXz9w" /><figcaption>Photo by <a href="https://unsplash.com/@jjying?utm_source=medium&amp;utm_medium=referral">JJ Ying</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>What is a linked list?</strong></h4><p>A linked list consists of nodes where each node represents the data field and its pointer value through which it acts like a linear data structure. Compared with arrays/slices, it doesn&#39;t store data contiguously. In a contiguous manner, we have an array data structure that follows us to store data in an adjacent mannered way like putting books alphabetically in a section. On the other hand, with a linked list data structure, we can take modern web browsers like Google Chrome, Firefox, etc. suppose, if we are on the website and we want to go back to the time of google search, we can just simply click on the back button of any web browser. It can also implement a stack, queue, tree and graph data structure.<br>There are two types of linked lists:<br>- Singly-linked list<br>- Doubly-linked list</p><p>Let’s get familiar with and get to know how to implement a singly linked list using crud operations in Go.</p><pre>//To checkout this example on playground and to get more insights, <br>//click on this link: https://go.dev/play/p/qOCFv47QMmB<br><br>//Singly-list data structure implementation<br>package main<br><br>//Define a Node struct with Value and Next<br>type Node struct {<br>  Value int<br>  Next *Node<br>}<br><br>//Define a LinkedList with Head and Tail<br>type LinkedList struct {<br>  Head *Node<br>  Tail *Node<br>}<br><br><br>/**<br> * description - linked list append/update operation(append means to add the <br> * element to the last of the list)<br> * @Input value - integer<br> * TC - O(1) | SC - O(1)<br>*/<br>func (l *LinkedList) Append(value int) {<br>  //Initialize a newNode variable and get the Node struct value<br>  newNode := &amp;Node{Value: value}<br>  /*<br>   If head == nil, then update the head and tail with newNode, else<br>   update the tail next to newNode and tail to newNode<br>  */ <br>  if l.Head == nil {<br>    l.Head = newNode<br>    l.Tail = newNode<br>  } else {<br>    l.Tail.Next = newNode<br>    l.Tail = newNode<br>  }<br>}<br><br><br>/*<br>  * description - linked list prepend/update operation(prepend means to add the <br>  * element to the front of the list)<br>  * @Input value - integer<br>  * TC - O(1) | SC - O(1)<br>*/<br>func (l *LinkedList) Prepend(value int) { <br>  //Initialize a newNode variable and get the Node struct value<br>  newNode := &amp;Node{Value: value}<br>  /*<br>   If head == nil, then update the head and tail with newNode, else<br>   newNode.Next-&gt;l.Head and l.Head-&gt;newNode<br>  */<br>  if l.Head == nil {<br>    l.Head = newNode<br>    l.Tail = newNode<br>  } else {<br>    newNode.Next = l.Head<br>    l.Head = newNode<br>  }<br>}<br><br><br>/**<br> * description - linked list delete operation<br> * @Input value - integer<br> * TC - O(1) | SC - O(1)<br>*/<br>func (l *LinkedList) Delete(value int) {<br>  if l.Head == nil {<br>    return<br>  }<br><br>  if l.Head.Value == value {<br>    l.Head = l.Head.Next<br>    return<br>  }<br>  <br>  currentNode := l.Head<br>  for currentNode.Next != nil {<br>    if currentNode.Next.Value == value {<br>      currentNode.Next = currentNode.Next.Next<br>      return<br>    }<br>  }<br>  currentNode = currentNode.Next<br>}<br><br>/**<br> * description - linked list read/find operation<br> * @Input value - integer<br> * @Output - Node struct.<br> * TC - O(N) | SC - O(1)<br>*/<br>func (l *LinkedList) Find(value int) *Node{<br>  currentNode := l.Head<br>  for currentNode != nil {<br>    if currentNode.Value == value {<br>      return currentNode<br>    }<br>    currentNode = currentNode.Next<br>  }<br>  return nil<br>}<br><br>func main() {<br>  //linked list create operation<br>  list := LinkedList{} <br>  list.Append(1)<br>  list.Append(2)<br>  list.Append(3)<br>  list.Append(4)<br><br>  //Find node with value 2<br>  findNode := list.Find(2)<br>  if findNode != nil {<br>    fmt.Println(&quot;Found node with value 2&quot;)<br>  }<br>  <br>  //Delete node with value 2<br>  list.Delete(2)<br>  <br>  //Find node with value 2<br>  node := list.Find(2)<br>  if node == nil {<br>    fmt.Println(&quot;Not able to find node with value 2&quot;)<br>  }<br>}<br><br>Output from the above code:<br>- Found node with value 2<br>- Not able to find node with value 2</pre><p>Below is the pictorial representation of the above methods invocation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vx5UIl0hr7rPkiX6uT8LPg.png" /><figcaption>Representation of linked list</figcaption></figure><h4>Why do we need to use a Doubly linked list?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*nF-hWVQOw_iKpUOlUNEzqA.png" /><figcaption>Double-linked list representation</figcaption></figure><p>The doubly linked list provides an extra hand with the pointers where we can add the pointer before and after the node. It means deleting, traversing and reversing would be easy, also it can grow and shrink easily, but as we all know everything good comes with some extra effort. So, with the addition of pointers and also if we&#39;re deleting or manipulating a list, it will require extra memory because of extra pointers implementation. Well, that’s a doubly linked list in a nutshell.</p><p>Let’s try to implement linked list construction using a doubly-linked list data structure.</p><pre>//To checkout this example on playground and to get more insights, <br>//click on this link: https://go.dev/play/p/VFNves2hyeD<br><br>//Doubly-linked list data structure implementation<br>package main<br><br>//Define a Node struct with Value and Next<br>type Node struct {<br>  Value int<br>  Next *Node<br>  Prev *Node<br>}<br><br>//Define a Node struct with Head, Tail and Size<br>type DoublyLinkedList struct {<br>  Head *Node<br>  Tail *Node<br>  Size int<br>}<br><br><br>/*<br>  * description - linked list append/update operation(append means to add the <br>  * element to the last of the list)<br>  * @Input value - integer<br>  * TC - O(1) | SC - O(1)<br>*/<br>func (list *DoublyLinkedList) Append(value int) {<br>  newNode := &amp;Node{Value: value}<br>  if list.Size == 0 {<br>    list.Head = newNode<br>    list.Tail = newNode<br>  } else {<br>    list.Tail.Next = newNode<br>    newNode.Prev = list.Tail<br>    list.Tail = newNode<br>  }<br>  list.Size++<br>}<br><br><br>/*<br>  * description - linked list prepend/update operation(prepend means to add the <br>  * element to the front of the list)<br>  * @Input value - integer<br>  * TC - O(1) | SC - O(1)<br>*/<br>func (list *DoublyLinkedList) Prepend(value int) {<br>  newNode := &amp;Node{Value: value}<br>  if list.Size == 0 {<br>    list.Head = newNode<br>    list.Tail = newNode<br>  } else {<br>    list.Head.Prev = newNode<br>    newNode.Next = list.Head<br>    list.Head = newNode<br>  }<br>  list.Size++<br>}<br><br><br>/*<br>  * description - linked list delete operation<br>  * TC - O(1) | SC - O(1)<br>*/<br>func (list *DoublyLinkedList) DeleteHead() {<br>  if list.Size == 0 {<br>    return<br>  }<br>  if list.Size == 1 {<br>    list.Head = nil<br>    list.Tail = nil<br>  } else {<br>    list.Head = list.Head.Next<br>    list.Head.Next = nil<br>  }<br>  list.Size--<br>}<br><br><br>/*<br>  * description - linked list delete operation<br>  * TC - O(1) | SC - O(1)<br>*/<br>func (list *DoublyLinkedList) DeleteTail() {<br>  if list.Size == 0 {<br>    return<br>  }<br>  if list.Size == 1 {<br>    list.Head = nil<br>    list.Tail = nil<br>  } else {<br>    list.Tail = list.Tail.Prev<br>    list.Tail.Next = nil<br>  }<br>  list.Size--<br>}<br><br><br>/**<br> * description - linked list read/find operation<br> * @Input value - integer<br> * @Output - Node struct.<br> * TC - O(N) | SC - O(1)<br>*/<br>func (list *DoublyLinkedList) Find(value int) *Node {<br> currentNode := list.Head<br> for currentNode != nil {<br>  if currentNode.Value == value {<br>   return currentNode<br>  }<br>  currentNode = currentNode.Next<br> }<br> return nil<br>}<br><br>func main() {<br> //linked list create operation<br> list := DoublyLinkedList{}<br> list.Append(1)<br> list.Append(2)<br> list.Append(3)<br> list.Append(4)<br> list.DeleteTail()<br> list.DeleteHead()<br><br> findNode := list.Find(2)<br> if findNode != nil {<br>  fmt.Println(&quot;Found node with value 2&quot;)<br> }<br><br> node := list.Find(4)<br> if node == nil {<br>  fmt.Println(&quot;Not able to find node with value 4&quot;)<br> }<br>}<br><br>Output from the above code:<br>- Found node with value 2<br>- Not able to find node with value 4</pre><h3>HashMaps and HashSets</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*weT0Et9Ub47_4qJ1" /><figcaption>Photo by <a href="https://unsplash.com/@abischreider?utm_source=medium&amp;utm_medium=referral">Abi Schreider</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>What are hashmaps?</h4><p>Hashmaps is an implementation of Hashtable that is already built-in Go.</p><blockquote>A hash table is a data structure that is used to store and retrieve elements using keys. It works by using a hash function to map keys to indexes in an array, and stores the elements at those indexes. When you want to retrieve an element, you use the same hash function to map the key to the index and retrieve the element. This makes it possible to perform operations like insertion, deletion, and lookup in constant time, on average.</blockquote><h4>When do we need HashMaps and HashSets?</h4><p>Hashmaps and Hashsets have one thing in common which is hashing by which they store and retrieve elements. Hashmaps, stores data in k<strong>ey-value pairs</strong> while HashSets hold <strong>unique elements.</strong> We need hashmaps when we need to perform frequent lookups let’s say while indexing a SQL query or implementing a cache using Redis and we need hash sets to store the unique element in the collection, remove duplicates from collections etc.</p><p>As hashmaps will have the same features as hashtables, we can store and retrieve data using keys. It is much faster than hash sets in terms of insertion, deletion and lookups of elements. It is also safe for concurrent use by multiple goroutines.</p><p>First, let’s implement a hashmap using an in-built <strong>map</strong> type.</p><pre>//To checkout this example on playground and to get more insights, <br>//click on this link: https://go.dev/play/p/Z9ODzU9re8M<br><br>//Hashmap implementation<br>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br>  //Initialize a map to store key/value pairs<br>  m := make(map[string]int)<br> <br>  //Insert key/values pairs in a map<br>  m[&quot;moon&quot;] = 1<br>  m[&quot;sun&quot;] = 2<br>  m[&quot;earth&quot;] = 3<br>  <br>  //Retrieve values from a map<br>  for k, v := range m {<br>    fmt.Printlf(&quot;&#39;%s&#39;: %d\n&quot;, k, v)<br>  }<br><br>  //Delete value from a map<br>  delete(m, &quot;moon&quot;)<br>  <br>  //Check if value exists in a map<br>  _, ok := m[&quot;pluto&quot;]<br>  if !ok {<br>    fmt.Printf(&quot;Key &#39;%s&#39; does not exist in the map&quot;, &quot;pluto&quot;)<br>  }<br>}<br><br>Output from the above code:<br>- &#39;moon&#39;: 1<br>  &#39;sun&#39;: 2<br>  &#39;earth&#39;: 3<br>- Key &#39;pluto&#39; does not exist in the map</pre><p>Implementation of a hashmap without built-in Golang methods, so let’s design a hashmap using golang. We can implement the same using <strong>structs</strong>, <strong>arrays</strong> and <strong>linked-list</strong>.</p><pre>//To checkout this example on playground and to get more insights, <br>//click on this link: https://go.dev/play/p/Kah6x-O__RN<br><br>// Design hashmap implementation<br>package main<br><br>import &quot;fmt&quot;<br><br>// Default value for tableSize is 10, just for code implementation<br>// In practice, the size of the hash table would depend on the <br>// expected size of the key-value pairs and the desired load factor <br>// of the hash table.<br>const tableSize = 10<br><br>// To store key-value pairs<br>type node struct {<br> key   string<br> value int<br> next  *node<br>}<br><br>// Define a hashmap struct<br>type hashmap struct {<br> table [tableSize]*node<br>}<br><br>/*<br> * Description - hashing function to insert a key-value pair into the hashmap<br> * @Input - key string<br> * @Output - integer<br> * TC - O(N) | SC - O(1)<br> */<br>func hash(key string) int {<br> sum := 0<br> for _, c := range key {<br>  sum += int(c)<br> }<br> return sum % tableSize<br>}<br><br>/*<br> * Description - To insert a key-value pair into the hashmap<br> * @Input - key string, value int<br> * TC - O(N) | SC - O(1)<br> */<br>func (m *hashmap) insert(key string, value int) {<br> //compute hash value<br> index := hash(key)<br><br> //Check if key already exists in hashmap<br> if m.contains(key) {<br>  return<br> }<br><br> //Create a newNode for the key-value pair<br> newNode := &amp;node{key, value, nil}<br><br> //Insert node at head of the hashmap<br> if m.table[index] == nil {<br>  m.table[index] = newNode<br> } else {<br>  newNode.next = m.table[index]<br>  m.table[index] = newNode<br> }<br>}<br><br>/*<br> * Description - To get the list with given key<br> * @Input - key string, value int<br> * @Output - Integer<br> * TC - O(N) | SC - O(1)<br> */<br>func (m *hashmap) get(key string) int {<br> //compute hash value<br> index := hash(key)<br><br> //Traverse the hashmap<br> //If currentHash is found, then return currentHash value, else update<br> //currentHash to next<br> //else return -1<br> currentHash := m.table[index]<br> for currentHash != nil {<br>  if currentHash.key == key {<br>   return currentHash.value<br>  }<br>  currentHash = currentHash.next<br> }<br> return -1<br>}<br><br>/*<br> * Description - To check if given key is in the hashmap<br> * @Input - key string<br> * @Output - Boolean<br> * TC - O(N) | SC - O(1)<br> */<br>func (m *hashmap) contains(key string) bool {<br> //compute hash value<br> index := hash(key)<br><br> //Traverse the hashmap<br> //If currentHash is found, then return currentHash value, else update<br> //currentHash to next<br> //else return -1<br> currentHash := m.table[index]<br> for currentHash != nil {<br>  if currentHash.key == key {<br>   return true<br>  }<br>  currentHash = currentHash.next<br> }<br> return false<br>}<br><br>func main() {<br> //Initialize a hashmap<br> m := hashmap{}<br><br> m.insert(&quot;foo&quot;, 0)<br> m.insert(&quot;bar&quot;, 1)<br> m.insert(&quot;bus&quot;, 2)<br><br> fmt.Println(m.get(&quot;bar&quot;)) // 1<br> fmt.Println(m.contains(&quot;bus&quot;)) // true<br> fmt.Println(m.contains(&quot;footer&quot;)) // false<br>}<br><br>Output from the above code:<br>- 1<br>- true<br>- false</pre><h3>Stacks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9zv9hMtzDbJ1kFoh" /><figcaption>Photo by <a href="https://unsplash.com/@sharonmccutcheon?utm_source=medium&amp;utm_medium=referral">Alexander Grey</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Stack follows the <strong>LIFO</strong> principle. The stack is like a stack of books if we want to read the topmost book, we can <strong>pop() </strong>the latest book, and if we want to add a new book to the stack via <strong>push(). </strong>In terms of Go, we can implement stack data structure with the help of <strong>slices </strong>and <strong>structs.</strong> Here’s a code implementation for the same.</p><pre>//To checkout this example on playground and to get more insights, <br>//click on this link: https://go.dev/play/p/rRQCcBeNOUU<br><br>package main<br><br>//Define a Stack struct with items array of type int<br>type Stack struct{<br>   items []int<br>}<br><br>/*<br> * Description - Push() function to push values to the stack<br> * @Input - i -&gt; Integer<br> * TC - O(1) | SC - O(1)<br>*/<br>func (s *Stack) push(i int) {<br>   s.items = append(s.items, i)<br>}<br><br>/*<br> * Description - Pop() function to pop/remove values from stack<br> * @Output -&gt; Integer<br> * TC - O(1) | SC - O(1)<br>*/<br>func (s *Stack) pop() int {<br>   //get the last from the stack length<br>   last := len(s.items) - 1<br>   removeAt := s.items[last]<br>   //re-slicing the items by removing the last item<br>   s.items = s.items[:last]<br>   return removeAt<br>}<br><br>/*<br> * Description - Peek() function to get the last value from the stack<br> * TC - O(1) | SC - O(1)<br>*/<br>func (s *Stack) peek() {<br>  last:= len(s.items) - 1<br>  peek := s.items[last]<br>  fmt.Println(peek)<br>}<br><br>func main(){<br>  stack := Stack{}<br>  stack.push(1)<br>  stack.push(2)<br>  stack.push(3)<br>  stack.pop() // 3<br>  stack.peek() // 2<br>  fmt.Println(stack) // {[1 2]}<br>}<br><br>Output from the above code:<br>- 3<br>- 2<br>- {[1 2]}</pre><h4>When do we need to use stacks?</h4><p>We need stacks when we need to keep track of the sequence of elements. <br>Let’s take an example, suppose you define a function which computes a sum of values and pushes its memory address on the call stack, then after complete execution that function got popped out from the stack. This mechanism leads to recursion which we use when we want to call the function by itself. But there is another thing too, there is a concept called <strong>closure</strong> which also gets benefits from this mechanism this works more on the scope level means even after the inner function execution we still have the scope for the outer function variable means even after the memory address popped out from the stack. Strange isn’t it?</p><p>Let’s try to implement min-max construction with stack using Go. To implement this we need to implement two structs via achieving struct embedding and also we need to implement two slices/arrays to store our data.</p><pre>//To checkout this example on playground and to get more insights, <br>//click on this link: https://go.dev/play/p/IyuWC3StXA9<br><br>// Min max construction<br>package main<br><br>import &quot;fmt&quot;<br><br>// MinMaxStack<br>type MinMaxStack struct {<br> stack       []int<br> minMaxStack []entry<br>}<br><br>// Entry<br>type entry struct {<br> min int<br> max int<br>}<br><br>/*<br> * Description - NewMinMaxStack() Create empty stack<br> * TC - O(1) | SC - O(1)<br> */<br>func NewMinMaxStack() *MinMaxStack {<br> return &amp;MinMaxStack{}<br>}<br><br>/*<br> * Description - Peek() function to get the last value from the stack<br> * @Output - Integer<br> * TC - O(1) | SC - O(1)<br> */<br>func (s *MinMaxStack) Peek() int {<br> return s.stack[len(s.stack)-1]<br>}<br><br>/*<br> * Description - Pop() function to pop the last value from the stack<br> * @Output - Integer<br> * TC - O(1) | SC - O(1)<br> */<br>func (s *MinMaxStack) Pop() int {<br> s.minMaxStack = s.minMaxStack[:len(s.minMaxStack)-1]<br> lastElem := len(s.stack) - 1<br> out := s.stack[lastElem]<br> s.stack = s.stack[:lastElem]<br> return out<br>}<br><br>/*<br> * Description - Push() function to push the values into the stack<br> * @Input number - int<br> * @Output - Pushed element<br> * TC - O(1) | SC - O(1)<br> */<br>func (s *MinMaxStack) Push(number int) {<br> newMinMaxStack := entry{min: number, max: number}<br> if len(s.minMaxStack) &gt; 0 {<br>  lastMinMax := s.minMaxStack[len(s.minMaxStack)-1]<br>  newMinMaxStack.min = min(lastMinMax.min, number)<br>  newMinMaxStack.max = max(lastMinMax.max, number)<br> }<br> s.minMaxStack = append(s.minMaxStack, newMinMaxStack)<br> s.stack = append(s.stack, number)<br>}<br><br>/*<br> * Description - GetMin() function to get the minimum value from stack<br> * @Output - Integer<br> * TC - O(1) | SC - O(1)<br> */<br>func (s *MinMaxStack) GetMin() int {<br> return s.minMaxStack[len(s.minMaxStack)-1].min<br>}<br><br>/*<br> * Description - GetMax() function to get the maximum value from stack<br> * @Output - Integer<br> * TC - O(1) | SC - O(1)<br> */<br>func (s *MinMaxStack) GetMax() int {<br> return s.minMaxStack[len(s.minMaxStack)-1].max<br>}<br><br>/*<br> * Description - min() function to find the minimum value<br> * @Input a - int, b - int<br> * @Output - Integer<br> * TC - O(1) | SC - O(1)<br> */<br>func min(a, b int) int {<br> if a &lt; b {<br>  return a<br> }<br> return b<br>}<br><br>/*<br> * Description - max() function to find the maximum value<br> * @Input a - int, b - int<br> * @Output - Integer<br> * TC - O(1) | SC - O(1)<br> */<br>func max(a, b int) int {<br> if a &lt; b {<br>  return b<br> }<br> return a<br>}<br><br>func main() {<br> m := NewMinMaxStack()<br> m.Push(4)<br> fmt.Printf(&quot;Get minimum value: %d\n&quot;, m.GetMin())<br> fmt.Printf(&quot;Get maximum value: %d\n&quot;, m.GetMax())<br> fmt.Printf(&quot;Peek value: %d\n&quot;, m.Peek())<br> m.Push(5)<br> fmt.Printf(&quot;Get minimum value: %d\n&quot;, m.GetMin())<br> fmt.Printf(&quot;Get maximum value: %d\n&quot;, m.GetMax())<br> fmt.Printf(&quot;Peek value: %d\n&quot;, m.Peek())<br> m.Push(2)<br> fmt.Printf(&quot;Get minimum value: %d\n&quot;, m.GetMin())<br> fmt.Printf(&quot;Get maximum value: %d\n&quot;, m.GetMax())<br> fmt.Printf(&quot;Peek value: %d\n&quot;, m.Peek())<br> m.pop()<br> m.pop()<br> fmt.Printf(&quot;Get minimum value: %d\n&quot;, m.GetMin())<br> fmt.Printf(&quot;Get maximum value: %d\n&quot;, m.GetMax())<br> fmt.Printf(&quot;Peek value: %d\n&quot;, m.Peek())<br> fmt.Printf(&quot;MinMaxStack data: %v\n&quot;, *m)<br>}<br><br>Output from the above code:<br>- Get minimum value: 4<br>- Get maximum value: 4<br>- Peek value: 4<br>- Get minimum value: 4<br>- Get maximum value: 5<br>- Peek value: 5<br>- Get minimum value: 2<br>- Get maximum value: 5<br>- Peek value: 2<br>- Get minimum value: 4<br>- Get maximum value: 4<br>- Peek value: 4<br>- MinMaxStack data: {[4] [{4 4}]}</pre><h3>Queues</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LkvETpZHjM18gvUl" /><figcaption>Photo by <a href="https://unsplash.com/@adriendlf?utm_source=medium&amp;utm_medium=referral">Adrien Delforge</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It is implemented by enqueuing and dequeuing in an array data structure. It works on the <strong>FIFO</strong> principle. Basically, the queue is like people standing in a row of queues where they want to book a ticket for the movie. So, as the first customer comes he/she will go first hence we need to <strong>dequeue</strong> the queue, on the other hand, if a new customer comes in a row, then it will be<strong> enqueued</strong> to the queue. We can implement queues with <strong>slices</strong>, <strong>structs</strong> and <strong>linked-list</strong>. Here’s the implementation in go:</p><pre>//To checkout this example on playground and to get more insights, <br>//click on this link: https://go.dev/play/p/IyuWC3StXA9<br><br>//Queue implementation with slices<br>package main<br><br>import &quot;fmt&quot;<br><br>/*<br> * Description - Enqueue() appending element to the top of the queue.<br> * @Input queue - []int, elem - int<br> * @Output - Array of Integers<br> * TC - O(1) | SC - O(1)<br>*/<br>func enqueue(queue[] int, elem int) []int {<br>  queue = append(queue, elem)<br>  fmt.Println(&quot;Enqueued: &quot;, elem)<br>  return queue<br>} <br><br>/*<br> * Description - Dequeue() removing element from the first/front of the queue<br> * @Input queue - []int, elem- int<br> * @Output - Array of Integers<br> * TC - O(1) | SC - O(1)<br>*/<br>func dequeue(queue[] int) []int {<br>  elem := queue[0]<br>  fmt.Println(&quot;Dequeued: &quot;, elem)<br>  return queue[1:]<br>}<br><br>func main() {<br>  queue := make([]int, 0)<br>  queue = enqueue(queue, 10);<br>  queue = enqueue(queue, 20);<br>  queue = dequeue(queue);<br>  queue = enqueue(queue, 30);<br>  fmt.Println(&quot;Queue:&quot;, queue); // Queue: {[20 30]}<br>}<br><br>Output from the above code:<br>- Enqueued:  10<br>- Enqueued:  20<br>- Dequeued:  10<br>- Enqueued:  30<br>- Queue: {[20 30]}</pre><pre>//To checkout this example on playground and to get more insights, <br>//click on this link: https://go.dev/play/p/h49jZ00BHZM<br><br>// Queue implementation with structs<br>package main<br><br>import &quot;fmt&quot;<br><br>// Queue struct implements elements of array of integers<br>type Queue struct {<br> items []int<br>}<br><br>/*<br> * Description - Enqueue() appending element to the top of the queue.<br> * @Input - elem -&gt; Integer<br> * @Output -&gt; Array of Integers<br> * TC - O(1) | SC - O(1)<br> */<br>func (q *Queue) Enqueue(elem int) []int {<br> q.items = append(q.items, elem)<br> fmt.Println(&quot;Enqueued: &quot;, elem)<br> return q.items<br>}<br><br>/*<br> * Description - Dequeue() removing element from the first/front of the queue<br> * @Output -&gt; Array of Integers<br> * TC - O(1) | SC - O(1)<br> */<br>func (q *Queue) Dequeue() []int {<br> elem := q.items[0]<br> fmt.Println(&quot;Dequeued: &quot;, elem)<br> q.items = q.items[1:]<br> return q.items<br>}<br><br>func main() {<br> queue := Queue{}<br> queue.Enqueue(10)<br> queue.Enqueue(20)<br> queue.Dequeue()<br> queue.Enqueue(30)<br> queue.Enqueue(40)<br> queue.Enqueue(50)<br> queue.Dequeue()<br> fmt.Println(&quot;Queue:&quot;, queue) // Queue: {[30 40 50]}<br>}<br><br>Output from the above code:<br>- Enqueued:  10<br>- Enqueued:  20<br>- Dequeued:  10<br>- Enqueued:  30<br>- Enqueued:  40<br>- Enqueued:  50<br>- Dequeued:  20<br>- Queue: {[30 40 50]}</pre><p>As we can see in the case of both slices and structs, we successfully handled the enqueue() and dequeue() operations and got the desired output. There is a catch with both implementations is that in the dequeue function when we invoke it, the very first thing we are trying to get the first element value and store it in a variable, which creates a memory address in the heap, as we are never returning that variable it leads to memory leaks which use unnecessary memory from available memory, hence it can also lead to some performance issues. We can use the linked list data structure to handle these memory leaks with some in-built operations of <strong>containers/lists</strong>. Let’s implement that:</p><pre>//To checkout this example on playground and to get more insights, <br>//click on this link: https://go.dev/play/p/eHVP1acoAlI<br><br>// Queue implementation with linked-list<br>package main<br><br>//container/list - package implements doubly linked list<br>import (<br> &quot;container/list&quot;<br> &quot;fmt&quot;<br>)<br><br>func main() {<br> queue := list.New()<br> fmt.Println(&quot;Queue: &quot;, *queue) //Queue: &amp;{{0xc0000a0180 0xc0000a0180 &lt;nil&gt; &lt;nil&gt;} 0}<br> queue.PushBack(10)<br> queue.PushBack(20)<br> fmt.Println(&quot;After pushing values in queue: &quot;, *queue) //After pushing values in queue: {{0xc0000a01e0 0xc0000a0210 &lt;nil&gt; &lt;nil&gt;} 2}<br><br> front := queue.Front()<br> fmt.Println(&quot;Front: &quot;, *front) //Front: {0xc0000a8210 0xc0000a8180 0xc0000a8180 10}<br> queue.Remove(front)<br> fmt.Println(&quot;After removing front: &quot;, *queue) //After removing front:  {{0xc00010e210 0xc00010e210 &lt;nil&gt; &lt;nil&gt;} 1}<br>}<br><br>Output from the above code:<br>- Queue:  {{0xc00010e180 0xc00010e180 &lt;nil&gt; &lt;nil&gt;} 0}<br>- After pushing values in queue:  {{0xc00010e1e0 0xc00010e210 &lt;nil&gt; &lt;nil&gt;} 2}<br>- Front:  {0xc00010e210 0xc00010e180 0xc00010e180 10}<br>- After removing front:  {{0xc00010e210 0xc00010e210 &lt;nil&gt; &lt;nil&gt;} 1}</pre><h4>When do we need queues?</h4><p>We need queues as this data structure helps us to manage the scheduling and automation part easily. Let’s take an example of go scheduler, i.e go runtime creates an OS thread(M) and with it also creates a logical processor(P) and goroutines with the context of both. Suppose, in our local run queue we have goroutines queued as G2-&gt;G3-&gt;G4. Suppose, there is a goroutine which is in the stack and its state updates from runnable to complete, then its memory address will get popped out and as there are other goroutines in the queue will process accordingly. So, go internals uses queues to operate synchronous and asynchronous context switching.</p><h3>Trees</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*suDj2gMEeOulBGsO" /><figcaption>Photo by <a href="https://unsplash.com/@milatovar?utm_source=medium&amp;utm_medium=referral">Mila Tovar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A tree data structure is a collection of nodes where the root node is at the topmost node and the leaf nodes act like child nodes. A real-world example of a tree is a DOM tree in HTML, where a model creates different types of HTML elements in a form of a tree, also some databases use trees to organize and structure their data. A tree could be efficient if we need to use insert, delete and search operations etc. Tree data structure could be of types like binary trees, binary search trees, Tries etc.</p><p>Let’s implement trees using golang:</p><pre>//To checkout this example on playground and to get more insights, <br>//click on this link: https://go.dev/play/p/Pmd2GsWeBTD<br><br>//Tree implementation<br>package main<br><br>import &quot;fmt&quot;<br><br>//Define a TreeNode struct with value, left and right<br>type TreeNode struct {<br> value int<br> left  *TreeNode<br> right *TreeNode<br>}<br><br>/*<br> * Description - preOrderTraversal() - to add to root first, <br> * then left and right nodes<br> * @Input - node -&gt; *TreeNode<br> * TC - O(n) | SC - O(1)<br> */<br>func preOrderTraversal(node *TreeNode) {<br> if node == nil {<br>  return<br> }<br><br> fmt.Println(node.value, &quot; &quot;)<br> preOrderTraversal(node.left)<br> preOrderTraversal(node.right)<br>}<br><br>/*<br> * Description - postOrderTraversal() - to add to left and right nodes first, then root node<br> * @Input - node -&gt; *TreeNode<br> * TC - O(n) | SC - O(1)<br> */<br>func postOrderTraversal(node *TreeNode) {<br> if node == nil {<br>  return<br> }<br><br> preOrderTraversal(node.left)<br> preOrderTraversal(node.right)<br> fmt.Println(node.value, &quot; &quot;)<br>}<br><br>/*<br> * Description - postOrderTraversal() - to add left node, then root node and at last right node<br> * @Input - node -&gt; *TreeNode<br> * TC - O(n) | SC - O(1)<br> */<br>func inOrderTraversal(node *TreeNode) {<br> if node == nil {<br>  return<br> }<br><br> preOrderTraversal(node.left)<br> fmt.Println(node.value, &quot; &quot;)<br> preOrderTraversal(node.right)<br>}<br><br>func main() {<br> root := &amp;TreeNode{value: 1}<br><br> // Add child nodes to the root node<br> root.left = &amp;TreeNode{value: 2}<br> root.right = &amp;TreeNode{value: 3}<br><br> // Add child nodes to the left child node<br> root.left.left = &amp;TreeNode{value: 4}<br> root.left.right = &amp;TreeNode{value: 5}<br><br> // Add child nodes to the right child node<br> root.right.left = &amp;TreeNode{value: 6}<br> root.right.right = &amp;TreeNode{value: 7}<br><br> // Traverse the binary tree<br> fmt.Println(&quot;Pre-Order Traversal:&quot;)<br> preOrderTraversal(root)<br> // Pre-Order Traversal: 1 2 4 5 3 6 7<br><br> fmt.Println(&quot;\nIn-Order Traversal:&quot;)<br> inOrderTraversal(root)<br> // In-Order Traversal: 2 4 5 1 3 6 7  <br><br> fmt.Println(&quot;\nPost-Order Traversal:&quot;)<br> postOrderTraversal(root)<br> // Post-Order Traversal: 2 4 5 3 6 7 1  <br>}<br><br>Output from the above code:<br>Pre-Order Traversal:<br>1  <br>2  <br>4  <br>5  <br>3  <br>6  <br>7  <br><br>In-Order Traversal:<br>2  <br>4  <br>5  <br>1  <br>3  <br>6  <br>7  <br><br>Post-Order Traversal:<br>2  <br>4  <br>5  <br>3  <br>6  <br>7  <br>1  </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*7u8duobc2ob9g7yTem6MMA.png" /><figcaption>Tree data structure representation in golang</figcaption></figure><h4>How trees are important and when do we need to use them?</h4><p>Trees follow hierarchical aka parent-child architecture by which we can create file systems, folder structures, database indexing etc.</p><h4>Binary Search Tree</h4><p>In a binary search tree, the left child nodes will always be less than the root node value and the right child nodes and the right child, node will always be greater than the root. Searching and insertion property becomes efficient with BSTs. Let’s implement BST in Go by using these properties.</p><pre>//To checkout this example on playground and to get more insights, <br>//click on this link: https://go.dev/play/p/Y_wvHRJ472j<br><br>//BST implementation<br>package main<br><br>import &quot;fmt&quot;<br><br>// Define TreeNode struct with Key, Left and Right<br>type TreeNode struct {<br> Key   int<br> Left  *TreeNode<br> Right *TreeNode<br>}<br><br>/*<br> * Description - Insert a key to a TreeNode<br> * @Input() - key -&gt; integer<br> * TC - O(logn) | SC - O(1)<br>*/<br>func (node *TreeNode) Insert(key int) {<br> if node.Key &lt; key {<br>  if node.Right == nil {<br>   node.Right = &amp;TreeNode{Key: key}<br>  } else {<br>   node.Right.Insert(key)<br>  }<br> } else if node.Key &gt; key {<br>  if node.Left == nil {<br>   node.Left = &amp;TreeNode{Key: key}<br>  } else {<br>   node.Left.Insert(key)<br>  }<br> }<br>}<br><br>/*<br> * Description - Search a key in TreeNode<br> * @Input() - key -&gt; Integer<br> * @Output() -&gt; Boolean<br> * TC - O(logn) | SC - O(1)<br>*/<br>func (node *Node) Search(key int) bool {<br> if node == nil {<br>  return false<br> }<br> if node.Key &lt; key {<br>  return node.Right.Search(key)<br> } else if node.Key &gt; key {<br>  return node.Left.Search(key)<br> }<br> return true<br>}<br><br>func main() {<br> tree := &amp;Node{Key: 100}<br> tree.Insert(50)<br> tree.Insert(300)<br> tree.Insert(30)<br> tree.Insert(88)<br> tree.Insert(231)<br> fmt.Println(&quot;Tree:&quot;, *tree) //{100 0xc00010a000 0xc00010a018}<br> fmt.Println(tree.Search(77)) //false<br> fmt.Println(tree.Search(88)) //true<br>}<br><br>Output from the above code:<br>- Tree: {100 0xc000010030 0xc000010048}<br>- false<br>- true</pre><h3>Heap</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IJPMzpJX7YCRiDEm" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>What is Heap and when do we need to use this data structure?</h4><p>A heap is a data structure that is used to maintain a collection of elements, where each element has a priority or key. A heap can be either a max heap or a min heap, depending on whether the highest priority element or the lowest priority element is at the root of the heap, respectively.</p><p>We need heaps when we need to maintain the collection of elements inefficiently with priorities like priority queues, sorting, memory management etc. The garbage collector in golang also uses heaps to allocate/deallocate data.</p><h4>Binary heap</h4><p>A Binary heap is a data structure that is used to implement priority queues which means the highest priority element will be stored at the root of the heap. A binary heap acts like a max heap means every parent node is greater than or equal to its child nodes means maximum values get stored at the root of the heap. Let’s see this by binary heap implementation:</p><pre>//To checkout this example on playground and to get more insights, <br>//click on this link: https://go.dev/play/p/oniegUJ64mz<br><br>// Binary/Max heap implementation<br>package main<br><br>import &quot;fmt&quot;<br><br>//Define a BinaryHeap struct with values of type array of integers<br>type BinaryHeap struct {<br> values []int<br>}<br><br>/*<br>  * Description - To insert values in heap<br>  * @Input() - val -&gt; integer<br>  * TC - O(N) | SC - O(1)<br>*/ <br>func (b *BinaryHeap) insert(val int) {<br> b.values = append(b.values, val)<br> b.siftUp(len(b.values) - 1)<br>}<br><br>/*<br>  * Description - To shift up the nodes<br>  * @Input() - index -&gt; integer<br>  * TC - O(logN) | SC - O(1)<br>*/<br>func (b *BinaryHeap) siftUp(index int) {<br> for index &gt; 0 {<br>  parentIndex := (index - 1) / 2<br>  if b.values[index] &lt;= b.values[parentIndex] {<br>   break<br>  }<br>  //Swap the indexes<br>  b.values[index], b.values[parentIndex] = b.values[parentIndex], b.values[index]<br>  index = parentIndex<br> }<br>}<br><br>/*<br>  * Description - To shift down the nodes<br>  * @Input() - index -&gt; integer<br>  * TC - O(logN) | SC - O(1)<br>*/<br>func (b *BinaryHeap) siftDown(index int) {<br> for {<br>  left := 2*index + 1<br>  right := 2*index + 2<br>  largest := index<br>  if left &lt; len(b.values) &amp;&amp; b.values[left] &gt; b.values[largest] {<br>   largest = left<br>  }<br>  if right &lt; len(b.values) &amp;&amp; b.values[right] &gt; b.values[largest] {<br>   largest = right<br>  }<br>  if largest == index {<br>   break<br>  }<br>  b.values[index], b.values[largest] = b.values[largest], b.values[index]<br>  index = largest<br> }<br>}<br><br>/*<br>  * Description - Peek the element<br>  * @Output() -&gt; Integer<br>  * TC - O(1) | SC - O(1)<br>*/<br>func (b *BinaryHeap) peek() int {<br> if len(b.values) == 0 {<br>  return 0<br> }<br> return b.values[0]<br>}<br><br>/*<br>  * Description - Pop the element<br>  * @Output() -&gt; Integer<br>  * TC - O(1) | SC - O(1)<br>*/<br>func (b *BinaryHeap) pop() int {<br> if len(b.values) == 0 {<br>  return 0<br> }<br> parentIndex := len(b.values) - 1<br> max := b.values[0]<br> b.values[0], b.values[parentIndex] = b.values[parentIndex], b.values[0]<br> b.values = b.values[:parentIndex]<br> b.siftDown(0)<br> return max<br>}<br><br>func main() {<br> heap := &amp;BinaryHeap{}<br> heap.insert(5)<br> heap.insert(10)<br> fmt.Printf(&quot;Peek value: %d\n&quot;, heap.peek())<br> heap.insert(3)<br> heap.insert(23)<br> heap.insert(33)<br> fmt.Printf(&quot;Pop value: %d\n&quot;, heap.pop())<br> heap.insert(12)<br> fmt.Printf(&quot;Peek value: %d\n&quot;, heap.peek())<br> fmt.Printf(&quot;Binary heap: %v\n&quot;, heap.values)<br>}<br><br>Ouput from the above code:<br>- Peek value: 10<br>- Pop value: 33<br>- Peek value: 23<br>- Binary heap: [23 12 3 5 10]</pre><h4>Min heap</h4><p>In a min heap data structure is opposite of obviously max heaps means the parent node is less than or equal to its child nodes.</p><p>Let’s implement a min heap construction.</p><pre>//To checkout this example on playground and to get more insights, <br>//click on this link: https://go.dev/play/p/G_qSMtcAfao<br><br>// Min Heap construction<br>package main<br><br>import &quot;fmt&quot;<br><br>// Define a MinHeap with heap of type array of integer<br>type MinHeap struct {<br> heap []int<br>}<br><br>/*<br> * Description - Return the parent index<br> * @Input() - i -&gt; Integer<br> * @Output() -&gt; Integer<br> * TC - O(1) | SC - O(1)<br> */<br>func (m *MinHeap) parentIndex(i int) int {<br> return (i - 1) / 2<br>}<br><br>/*<br> * Description - Return the left child index<br> * @Input() - i -&gt; Integer<br> * @Output() -&gt; Integer<br> * TC - O(1) | SC - O(1)<br> */<br>func (m *MinHeap) leftChildIndex(i int) int {<br> return 2*i + 1<br>}<br><br>/*<br> * Description - Return the right child index<br> * @Input() - i -&gt; Integer<br> * @Output() -&gt; Integer<br> * TC - O(1) | SC - O(1)<br> */<br>func (m *MinHeap) rightChildIndex(i int) int {<br> return 2*i + 2<br>}<br><br>/*<br> * Description - swap() the values in MinHeap<br> * @Input() - (i, j) -&gt; Integer<br> * TC - O(1) | SC - O(1)<br> */<br>func (h *MinHeap) swap(i, j int) {<br> h.heap[i], h.heap[j] = h.heap[j], h.heap[i]<br>}<br><br>/*<br> * Description - shift up the values<br> * TC - O(logN) | SC - O(1)<br> */<br>func (h *MinHeap) shiftUp() {<br> //Last element as current index<br> currentIndex := len(h.heap) - 1<br><br> /*<br>  * Check if currentIndex is greater than zero and if currentIndex in heap<br>  * is less than parent index in heap<br>  * if true, then swap the current index and parent index<br>  * update currentIndex with parentIndex<br>  */<br> for currentIndex &gt; 0 &amp;&amp; h.heap[currentIndex] &lt; h.heap[h.parentIndex(currentIndex)] {<br>  h.swap(currentIndex, h.parentIndex(currentIndex))<br>  currentIndex = h.parentIndex(currentIndex)<br> }<br>}<br><br>/*<br> * Description - shift down the values<br> * TC - O(1) | SC - O(1)<br> */<br>func (h *MinHeap) shiftDown() {<br> currentIndex := 0<br> /*<br>  * Check if left child index is less than length of heap<br>  * If right child index is less than heap and if heap of right child<br>  * index is less than heap of smaller child index,<br>  * then update smallerChildIndex with rightChildIndex<br>  * else, swap the rightChildIndex and smallerChildIndex<br>  * update currentIndex with smallerChildIndex<br>  */<br> for h.leftChildIndex(currentIndex) &lt; len(h.heap) {<br>  smallerChildIndex := h.leftChildIndex(currentIndex)<br>  if h.rightChildIndex(currentIndex) &lt; len(h.heap) &amp;&amp;<br>   h.heap[h.rightChildIndex(currentIndex)] &lt; h.heap[smallerChildIndex] {<br>   smallerChildIndex = h.rightChildIndex(currentIndex)<br>  }<br>  if h.heap[currentIndex] &lt; h.heap[smallerChildIndex] {<br>   break<br>  } else {<br>   h.swap(currentIndex, smallerChildIndex)<br>  }<br>  currentIndex = smallerChildIndex<br> }<br>}<br><br>/*<br> * Description - Get a peek at the minimum value from the heap<br> * @Output() -&gt; Integer<br> * TC - O(1) | SC - O(1)<br> */<br>func (h MinHeap) Peek() int {<br> if len(h.heap) == 0 {<br>  return -1<br> }<br> return h.heap[0]<br>}<br><br>/*<br> * Description - Push the value when appending the same in MinHeap<br> * @Output() - value - Integer<br> * TC - O(logn) | SC - O(1)<br> */<br>func (h *MinHeap) Push(value int) {<br> h.heap = append(h.heap, value)<br> h.shiftUp()<br>}<br><br>/*<br> * Description - length of the heap<br> * @Output() - Integer<br> * TC - O(1) | SC - O(1)<br> */<br>func (h MinHeap) length() int {<br> return len(h.heap)<br>}<br><br>/*<br> * Description - Pop the first element from the heap<br> * @Output() - Integer<br> * TC - O(1) | SC - O(1)<br> */<br>func (h *MinHeap) Pop() int {<br> if len(h.heap) == 0 {<br>  return -1<br> }<br> max := h.heap[0]<br> h.heap[0] = h.heap[len(h.heap)-1]<br> h.heap = h.heap[:len(h.heap)-1]<br> h.shiftDown()<br> return max<br>}<br><br>func main() {<br> heap := &amp;MinHeap{}<br> heap.Push(5)<br> heap.Push(10)<br> fmt.Printf(&quot;Peek value: %d\n&quot;, heap.Peek())<br> heap.Push(3)<br> heap.Push(23)<br> heap.Push(33)<br> fmt.Printf(&quot;Binary heap: %v\n&quot;, heap.heap)<br> fmt.Printf(&quot;Pop value: %d\n&quot;, heap.Pop())<br> heap.Push(12)<br> heap.Push(2)<br> fmt.Printf(&quot;Peek value: %d\n&quot;, heap.Peek())<br> fmt.Printf(&quot;Binary heap: %v\n&quot;, heap.heap)<br>}<br><br>Output from the above code: <br>- Peek value: 5<br>- Binary heap: [3 10 5 23 33]<br>- Pop value: 3<br>- Peek value: 2<br>- Binary heap: [2 10 5 23 12 33]</pre><h3>Graphs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tiRT0a7EYm2wHlrg" /><figcaption>Photo by <a href="https://unsplash.com/es/@pietrozj?utm_source=medium&amp;utm_medium=referral">Pietro Jeng</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It is a collection of vertices or nodes connected by edges. We use graphs data structure basically to solve networking systems, navigation systems, etc. In this, a brief explanation for graphs with space and time complexity is already explained on Wikipedia. For more details about graphs, follow this: <a href="https://en.wikipedia.org/wiki/Graph_(abstract_data_type)">https://en.wikipedia.org/wiki/Graph_(abstract_data_type)</a>.</p><p>Graphs could be represented in two ways:<br>- Adjacency matrix<br>- Adjacency list</p><h4>When do we need graphs data structure?</h4><p>We need graph data structure when we need to build a social media website like Facebook, or Twitter, etc. also when we are building routing algorithms like traffic routes, online delivery routes, navigation, etc. <br>The recommendation system also uses the same data structure for example, if a patient is medicated with XYZ medication previously, an AI-generated recommendation system could generate a medication flow accordingly to the patient’s current state.</p><h4>Adjacency list</h4><p>It is a graph which has a collection of lists in which each node in the graph has a list of adjacency nodes. We can create an adjacency list in go using struct and slices. Let’s implement an adjacency list graph:</p><pre>//To checkout this example on playground and to get more insights, <br>//click on this link: https://go.dev/play/p/J-vcGX7uIlS<br><br>// Graph adjacency list implementation<br>package main<br><br>import &quot;fmt&quot;<br><br>// Define a Graph struct with vertices of type Vertex<br>type Graph struct {<br> vertices []*Vertex<br>}<br><br>// Define a Vertex struct with key and adjacent<br>type Vertex struct {<br> key      int<br> adjacent []*Vertex<br>}<br><br>/*<br> * Description - Create New vertex<br> * @Output -&gt; Vertex struct<br> * TC - O(V^2) | SC - O(1)<br> */<br>func NewVertex(key int) *Vertex {<br> return &amp;Vertex{key: key}<br>}<br><br>/*<br> * Description - Add vertex in graph<br> * @Input - v -&gt; Vertex struct<br> * TC - O(1) | SC - O(1)<br> */<br>func (g *Graph) AddVertex(v *Vertex) {<br> g.vertices = append(g.vertices, v)<br>}<br><br>/*<br> * Description - Add edge graph<br> * @Input - (from, to)-&gt; Vertex struct<br> * TC - O(1) | SC - O(1)<br> */<br>func (g *Graph) AddEdge(from, to *Vertex) {<br> from.adjacent = append(from.adjacent, to)<br> to.adjacent = append(to.adjacent, from)<br>}<br><br>/*<br> * Description - To print all the vertices and adjacent list<br> * TC - O(E) | SC - O(1)<br> */<br>func (g *Graph) Print() {<br> for _, v := range g.vertices {<br>  fmt.Printf(&quot;Vertex %d:&quot;, v.key)<br>  for _, adj := range v.adjacent {<br>   fmt.Printf(&quot;  %d&quot;, adj.key)<br>  }<br>  fmt.Println()<br> }<br>}<br><br>func main() {<br> // Create the vertices<br> v1 := NewVertex(1)<br> v2 := NewVertex(2)<br> v3 := NewVertex(3)<br> v4 := NewVertex(4)<br><br> // Create the graph<br> g := &amp;Graph{}<br> g.AddVertex(v1)<br> g.AddVertex(v2)<br> g.AddVertex(v3)<br> g.AddVertex(v4)<br><br> // Create the edges<br> g.AddEdge(v1, v2)<br> g.AddEdge(v2, v3)<br> g.AddEdge(v3, v4)<br> g.AddEdge(v4, v1)<br><br> // Print the graph<br> g.Print()<br>}<br><br>Output from the above code:<br>- Vertex 1:  2  4<br>- Vertex 2:  1  3<br>- Vertex 3:  2  4<br>- Vertex 4:  3  1</pre><h4>Adjacency matrix</h4><p>It’s a graph which is a 2D array in which rows and columns represent vertices and values in an array represent edges. Let’s implement this in Go:</p><pre>//To checkout this example on playground and to get more insights, <br>//click on this link: https://go.dev/play/p/J-vcGX7uIlS<br><br>// Graph adjacency matrix implementation<br>package main<br><br>import &quot;fmt&quot;<br><br>// Define a Graph struct with matrix and size<br>type Graph struct {<br> matrix [][]int<br> size   int<br>}<br><br>/*<br> * Description - Add new graph<br> * @Input - size -&gt; Integer<br> * TC - O(V^2) | SC - O(N)<br> */<br>func NewGraph(size int) *Graph {<br> g := &amp;Graph{matrix: make([][]int, size)}<br> for i := 0; i &lt; size; i++ {<br>  g.matrix[i] = make([]int, size)<br> }<br> return g<br>}<br><br>/*<br> * Description - Add new edge in graph<br> * @Input - (from, to, weight) -&gt; Integer<br> * TC - O(1) | SC - O(1)<br> */<br>func (g *Graph) AddEdge(from, to, weight int) {<br> g.matrix[from][to] = weight<br>}<br><br>/*<br> * Description - remove edge from graph<br> * @Input - (from, to, weight) -&gt; Integer<br> * TC - O(1) | SC - O(1)<br> */<br>func (g *Graph) RemoveEdge(from, to int) {<br> g.matrix[from][to] = 0<br>}<br><br>/*<br> * Description - Check if graph has an edge<br> * @Input - (from, to)-&gt; Integer<br> * @Output - Boolean<br> * TC - O(1) | SC - O(1)<br> */<br>func (g *Graph) HasEdge(from, to int) bool {<br> return g.matrix[from][to] != 0<br>}<br><br>/*<br> * Description - Print matrix<br> * TC - O(V^2) | SC - O(1)<br> */<br>func (g *Graph) Print() {<br> for _, row := range g.matrix {<br>  fmt.Println(row)<br> }<br>}<br><br>func main() {<br> g := NewGraph(4)<br> g.AddEdge(0, 1, 1)<br> g.AddEdge(0, 2, 2)<br> g.AddEdge(1, 2, 3)<br> g.AddEdge(2, 1, 5)<br> fmt.Println(&quot;Before removing the edges from graph:&quot;)<br> g.Print()<br> g.RemoveEdge(2, 1)<br> g.AddEdge(3, 3, 4)<br> fmt.Printf(&quot;Edge exists: %v\n&quot;, g.HasEdge(3, 1))<br> g.AddEdge(2, 2, 7)<br> fmt.Printf(&quot;Edge exists: %v\n&quot;, g.HasEdge(2, 2))<br> fmt.Println(&quot;After removing the edges from graph:&quot;)<br> g.Print()<br>}<br><br>Output from the above code:<br>- Before removing the edges from graph:<br>  [0 1 2 0]<br>  [0 0 3 0]<br>  [0 5 0 0]<br>  [0 0 0 0]<br>- Edge exists: false<br>- Edge exists: true<br>- After removing the edges from graph:<br>  [0 1 2 0]<br>  [0 0 3 0]<br>  [0 0 7 0]<br>  [0 0 0 4]</pre><p>If you reach the end of the blog, hopefully, you got to learn how to implement all common data structures in Go.</p><blockquote>Do comment and give feedback if possible as it will improve me to provide valuable content. Stay tuned for more content related to LLD, design patterns and system design in Go.</blockquote><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20b652305934" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/data-structures-implementation-in-golang-20b652305934">Data structures implementation in Golang</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Client-Server model implementation in Golang]]></title>
            <link>https://nikhilvaidyar.medium.com/client-server-model-implementation-in-golang-3e2ee3613c08?source=rss-d2d76b301ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e2ee3613c08</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[client-server-model]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Nikhil Vaidyar]]></dc:creator>
            <pubDate>Thu, 08 Sep 2022 12:14:57 GMT</pubDate>
            <atom:updated>2022-09-08T12:14:57.245Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, I will try my best to explain the client and server model and how it is so important and how we use it daily in our assigned tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GVZkatYza7evJAcA" /><figcaption>Photo by <a href="https://unsplash.com/@lucian_alexe?utm_source=medium&amp;utm_medium=referral">Lucian Alex</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s start this topic with some real-world scenarios, right? So, let’s say we need to explain the client-server model in a simple daily life way. Suppose, you called a pizza delivery company called “YourPizzaBuddy” and then tell an executive on the other side asked you about the details like which pizza would you like to have and then you say I need margarita pizza with bell pepper toppings on it and some cold drinks too and then after some time this order got confirmed and after 30 minutes, you got your pizza delivered by pizza delivery guy. Well, that’s a system which is also a bit similar to the client-server model. Like, we as a client requested a response called pizza and from the server side, it was processing our order and we got pizza in response, the same thing we requested. Well, I will now explain this topic in a more technical way.</p><h3>What is the client-server model?</h3><p>It is a model in which the client is requesting data or some service which gets processed by the server and the server process the desired request which is coming from the client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*blYEIUaCXlcadrL59kxMgQ.png" /><figcaption>Client-server model representation</figcaption></figure><p>So, let&#39;s get a bit deep into this model, let’s say what happens when you type a URL on your internet browser like google chrome, safari etc. in response you get the desired webpage response. So, how does this happens actually?</p><p>When you type any URL on the search bar of the browser, that URL is actually mapped to a unique IP address and that IP is then mapped to a DNS, which describes the entities and protocols from DNS to IP address. Suppose, if we search for a URL that is not cached in our browser, what happens? Actually, in that case, if the URL is not in our browser and OS cache, then the resolver will ping to root and then root will provide the possible TLDs(Top-Level Domains) after that it will provide the name-server, hence the name-server is created when you register a domain, so domain name-servers provide stores with the IP address and hence you will get the desired result. Well, I got to learn all this from this website: <a href="https://howdns.works/">https://howdns.works</a>. They have described the whole journey of how DNS works in an interactive and fun way.</p><h3>Implementation using terminal</h3><p>Using the Netcat command, you can also create your client-server model in your OS terminal. It’s a command-line utility to do Read-Write operations on computer networks.</p><p>To start the server on your local machine, just open your terminal and type this command</p><pre>nc 127.0.0.1 8080</pre><p>This command starts the server on your terminal and with that, you can also open another terminal and type the command, it will listen on port 80 and show the response on the terminal which is listening from the system default host.</p><pre>nc -l 8080</pre><p>NC — means Netcat command<br>127.0.0.1 — It is a localhost address of a device<br>8080 — port</p><p>Here’s the representation for the above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*R0ezs3r7715FQAKfifGlGA.gif" /><figcaption>Implementation using terminal</figcaption></figure><h3>Implementation in golang</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GvFeUczUyT0PIHB9" /><figcaption>Photo by <a href="https://unsplash.com/@possessedphotography?utm_source=medium&amp;utm_medium=referral">Possessed Photography</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We can also implement the same in golang using goroutines. Goroutines are lightweight threads that work concurrently to achieve the output. Well, there’s more to goroutines, which I will explain in my upcoming series. Here’s the working of the client-server alike model using golang. We will create one client and server which will concurrently show the message coming from the server.</p><h4>Code implementation</h4><p>In the implementation of the server.go, we will create two functions one to handle the outgoing messages which are concurrently sending the “<strong><em>Hi from server</em></strong>” message to the client which is listening on port 8080. Whereas, with the implementation of the client.go it reads and write the I/O to the terminal.</p><h4>Server</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lvx-zCkO6F9ZWVI5ur5wzg.png" /><figcaption>server</figcaption></figure><h4>Client</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNoBTWX95wLGacsR5A6xlg.png" /><figcaption>client</figcaption></figure><p>From the above approach, you will get the desired output and get to know the importance of goroutines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*fCQK9W5ibdMM7wxqVXFi9g.gif" /><figcaption>Implementation using golang</figcaption></figure><p>I have also created a repository for the various upcoming system design fundamentals and we try to replicate the system design using golang. You can go out and check out this link: <a href="https://github.com/nikzayn/golang-system-design">https://github.com/nikzayn/golang-system-design</a>. Later on, I will explain the goroutines in a bit more detail.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e2ee3613c08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Functions in Golang]]></title>
            <link>https://nikhilvaidyar.medium.com/understanding-functions-in-golang-62e8dd18b929?source=rss-d2d76b301ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/62e8dd18b929</guid>
            <category><![CDATA[function]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[pointers]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Nikhil Vaidyar]]></dc:creator>
            <pubDate>Sun, 17 Jul 2022 13:54:13 GMT</pubDate>
            <atom:updated>2022-07-17T13:54:13.477Z</atom:updated>
            <content:encoded><![CDATA[<h4>Getting familiar with functions and how to implement and when to use them.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q88lyqlHxcgFepeHBHrvGA.jpeg" /><figcaption><a href="https://unsplash.com/photos/WlMaIRoh7j8">Pizza by Louis Hansel on Unsplash</a></figcaption></figure><p>So, let’s start the topic with pizza. I am guessing that it’s the favorite food for most people. But to cook the best pizza requires the best combination of sauce, dough base, topping, etc. Making a delicious pizza requires different types of steps like first preparing the base with dough, then making that perfect sauce, then rolling out the dough, and at last top and baking. If we think a bit technically, these are nothing but small sets of functions divided into different parts that give the delicious result in the form of 🍕.</p><h3>What are functions or how do we use them and how it is different from methods?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*55xkbGmJhtQuvXfQHNWaTQ.jpeg" /><figcaption>xPhoto by <a href="https://unsplash.com/@sigmund?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sigmund</a> on <a href="https://unsplash.com/s/photos/computer-function?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In brief, functions are like simple tasks for which you give input to do something and you get the desired output. We follow functions in our daily lives like cooking food, delivering a letter, or booking a flight. We follow step by step process to complete the overall process. Coming to the context of Go, functions are expressed like this:</p><figure><img alt="Function representation of Go" src="https://cdn-images-1.medium.com/max/1024/1*EWhIvf04usnjeZ7xLZX67w.png" /><figcaption>Representation of a function in Go</figcaption></figure><p>As you can see above implementing a function in go is easy and clean. In this, our functionality is to find out the names based on their rank that could be related to marks for say. The parameters need to be defined first and then the type of the parameter should be accordingly to that. As Go is a statically typed language that restricts you from using loose data types. Below is a simple example of how you can use functions in Go: <a href="https://go.dev/play/pz/znF6bqobkOQ">https://go.dev/play/pz/znF6bqobkOQ</a></p><p>Methods are a bit more special than functions as they operate on the addition of parameters in the <em>func</em> keyword to specify the receiver of the method. I will explain this in more depth later.</p><h3>Declaration in functions</h3><p>In Go, we can declare functions using the <em>func </em>keyword where we can pass its parameters and return the type of function. Also, if we declare functions with capital letters they will become public and we can export them to different packages. Similarly, with a small case declaration, we can use that function in that particular package. <strong>Hence, encapsulation……….. </strong><br>Let’s see that with an example:</p><figure><img alt="Examples of private and public functions in Go" src="https://cdn-images-1.medium.com/max/1024/1*AOM-woEilv-M7XzBpPbfLg.png" /><figcaption>Examples of private and public functions in Go</figcaption></figure><p>Most programming languages have functions that accept multiple parameters but Go functions can also return multiple return types that give flexibility to a function to get desired output. Functions are reusable and it becomes easy to understand when it splits further. When functions are declared and if we initialize and declare one value inside, it becomes block-scoped to that function. It cannot be used outside the body of that function.</p><pre>func celsiusToFahrenheit(c float64) float64 {<br> f := (c * 9.0 / 5.0) + 32.0<br> fmt.Println(celsius)<br> return f<br>}</pre><pre>func main() {<br> celsius := 33.2<br> fahrenheit := celsiusToFahrenheit(celsius)<br> fmt.Println(fahrenheit, &quot;F°&quot;)<br>}</pre><p>Hence, we are now familiar with the function declaration, well there’s more in the crux table which is functional programming. Basically, in brief, it says that a function should be pure with no state mutation and side effects. We will get to know more about functional programming in Go in the upcoming blog series. Let’s get to know more about functions.</p><h3>What are first-class functions?</h3><p>First-class functions are like when functions are treated as variables or could be passed as an argument, or parameter, or we could also return multiple functions. Let’s get to know more about how we can use functions in different ways:</p><h4>Multiple return values</h4><p>In multiple return values, we can pass individual or multiple parameters and in return, we can multiple return values. It’s just simple as that nothing to put on. Let’s get familiar with an example:</p><pre>func multiplyValues(x int) (int, int) {<br>    return x * 3, x * 2<br>}</pre><pre>multiplyValues(3) // 9, 6</pre><h4>Assigning functions to variables</h4><p>Functions that are assigned via variables could be updated easily when we assign a different function to them. Let’s see with an example</p><pre>func areaOfSqaure() float64 {<br> return 45.4 * 45.4<br>}</pre><pre>func invalidArea() float64 {<br> return 0<br>}</pre><pre>func main() {<br> result := areaOfSqaure<br> fmt.Println(&quot;Result:&quot;, result()) // Result: 2061.16<br> result = invalidArea<br> fmt.Println(&quot;Result:&quot;, result()) // Result: 0<br>}</pre><h4>Higher-Order functions</h4><p>Functions that either accept a function as a type or return function. We can achieve code resuability with complex code readability while using HOF in Go. Let’s see with an example:</p><pre>func main() {<br> result := areaOfSquare()<br> displayResult(5, 5, result)<br>}</pre><pre>func areaOfSquare() func(int, int) int {<br> return func(x, y int) int {<br>  return x * y<br> }<br>}</pre><pre>func displayResult(x, y int, result func(int, int) int) {<br> fmt.Printf(&quot;Area of square: %d&quot;, result(x, y))<br>}</pre><p>Here, we have implemented two functions one with <em>areaOfSqaure </em>and <em>displayResult. </em>In the first function, we are passing a function return type as a function of type int and in the second function, we are passing a function as assigned with a variable <em>result </em>in function params.</p><h4>Passing functions to other functions</h4><p>In Go, the function can also be returned to another function as a return type. Let’s get familiar with an example:</p><pre>func functionReturnFunction() func() int {<br> i := 0<br> return func() int {<br>  i++<br>  return i * i<br> }<br>}</pre><pre>func main() {<br> i := functionReturnFunction()<br> j := functionReturnFunction()</pre><pre> fmt.Println(&quot;i1:&quot;, i())  // i1: 1<br> fmt.Println(&quot;i2:&quot;, i())  // i2: 4<br> fmt.Println(&quot;j1:&quot;, j())  // j1: 1<br> fmt.Println(&quot;j2:&quot;, j())  // j2: 4<br> fmt.Println(&quot;i3:&quot;, i())  // i3: 9<br>}</pre><p>As you can see above in <em>functionReturnFunction </em>we have initialized and declared variable “<em>i” </em>and also declared an anonymous function that can form <strong>closures. </strong>An anonymous function, also known as function literal in Go, means functions without a name. Function literals are <strong>closures </strong>because they keep references to the variables in the surrounding scope even after the function is successfully executed. So, here we can see that we have initialized and declared <em>functionReturnFunction </em>via variables like <em>i</em> and <em>j. </em>We see that when we are invoking both functions in different sequences the count of “i” will be maintained when we are invoking a function with the variable “i” and the same happens when we are invoking with the variable “j”. In conclusion, each function execution creates its own variable scope to maintain its functionality.</p><h4>Passing functions with pointer parameters</h4><p>Functions with pointer parameters are a pretty straightforward approach to using pointers in functions. In parameter, you need to define the type of parameter with pointer and when invoking the function, you just need to pass ampersand to the function invocation. Let’s see this in an example:</p><pre>func functionWithPointers(value *float64) float64 {<br> return *value * *value<br>}</pre><pre>func main() {<br> x := 88.4<br> fmt.Println(functionWithPointers(&amp;x)) //7814.560000000001</pre><pre> x = 80<br> fmt.Println(functionWithPointers(&amp;x)) //6400<br>}</pre><p>As pointers are stored in the memory address with the ampersand operator we can receive the memory address value as we can see in <em>functionWithPointers </em>the value which parameters take is dereferencing the value by putting * in front of the value.</p><h4>Functions with return type pointer</h4><p>In passing functions with pointer parameters as we saw that we can pass pointer types and with that, we can also pass the pointer types to the return values of the function. Let’s see with an example:</p><pre>func functionReturnPointers(v float64) *float64 {<br> x := v * v<br> return &amp;x<br>}</pre><pre>func main() {<br> result := functionReturnPointers(20.5)<br> fmt.Println(&quot;Dereference result:&quot;, *result) <br> // Dereference result: 420.25<br> fmt.Println(&quot;Without dereference result:&quot;, result)<br> // Without dereference result: 0xc000018030<br>}</pre><p>Hence, we get the desired result with the use of dereferencing the same as what we did above when we are invoking <em>functionWithPointers </em>we also first dereference the values, and when invoking with a memory address, we got the desired result. Suppose, if didn’t use dereference before the result variable, we get the memory address of that variable.</p><p>Well, there’s more to another type of function which are methods that accepts the receiver as a special parameter. I will discuss the same in upcoming blogs in detail and how it makes our code much more easier while implementing structs. Stay tuned…..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62e8dd18b929" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Achieve Principles of OOPs in Go]]></title>
            <link>https://medium.com/better-programming/how-to-achieve-principles-of-oops-in-go-6568f7b76f5f?source=rss-d2d76b301ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/6568f7b76f5f</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Nikhil Vaidyar]]></dc:creator>
            <pubDate>Thu, 16 Jun 2022 17:43:22 GMT</pubDate>
            <atom:updated>2022-06-16T18:06:36.582Z</atom:updated>
            <content:encoded><![CDATA[<h4>Getting familiar with OOPs concept in Go and understanding how Go achieves these principles in its own exceptional way</h4><figure><img alt="Red moon in darkness of universe" src="https://cdn-images-1.medium.com/max/1024/0*ulDnTOVEnIks4Dtz" /><figcaption>Photo by <a href="https://unsplash.com/@federize?utm_source=medium&amp;utm_medium=referral">Federico Beccari</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You can see above that there is an alluring red heavenly body that looks and describes a lot more than this picture in this darkness of the universe with millions of stars and planets away from it. Well, we can also relate the same to our topic today like the universe is a big <strong>class</strong> of objects means the sun, planets, moons, asteroids, etc, are all <strong>objects</strong> of that class. In fact, the moonlight also plays a role in <strong>inheritance</strong> the moonlight which is actually dependent on the sun’s light. Hence, we can relate OOP’s concepts to a lot of things. So, let’s get a bit more familiar in respect with Go.</p><h3>What are OOPs and why do we need to use them?</h3><p>OOPs stands for <em>Object-Oriented Programming Systems and </em>are the type of programming in which we need to define the data structure for the data type and the certain operation to modularize our program structure. For more, you can refer to this link: <a href="https://en.wikipedia.org/wiki/Object-oriented_programming">https://en.wikipedia.org/wiki/Object-oriented_programming</a></p><p>We need OOPs when we need to modularize our complex code structure, make it more reliable, and maintainable, provide a good framework for code libraries, etc.</p><h3>Does Go actually uses the OOPs concept or is it an OOP language?</h3><p>Let’s consider Go to be a light object-oriented programming language because of Go&#39;s simplicity. Go use the same alike concepts of OOPs but not all in one go. First of all, Go is not an OOP language and it is not designed to be like that because the principles of OOPs are designed to be consists of class and object structure to maintain the code infrastructure via implementing super class, abstract class, constructors, objects, derived class, and destructors, etc. Well, there is a lot to that. Talking about Go, it just implements its OOPs structure in its own way. Well, this debate can go long, but here’s an official FAQ answer available on this link: <a href="https://go.dev/doc/faq#Is_Go_an_object-oriented_language">https://go.dev/doc/faq#Is_Go_an_object-oriented_language</a>. Go check it out.</p><p>Here are some concepts of OOPs below with respect to Go, so let’s try to get familiar with them.</p><h4>Encapsulation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LrOvPSXUBcPkDO9n" /><figcaption>Photo by <a href="https://unsplash.com/@dtopkin1?utm_source=medium&amp;utm_medium=referral">Dayne Topkin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In simpler terms <a href="https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)">encapsulation</a> means if we have single entity data that is written inside any class or package it is hidden for another class or for the outside world whereas <a href="https://en.wikipedia.org/wiki/Abstraction_(computer_science)">abstraction</a> means to hide unnecessary information</p><p>In Go, we use this principle at package level because it doesn’t provide <a href="https://en.wikipedia.org/wiki/Access_modifiers">access modifiers</a> like private, public, and protected. It also plays a role in variables, structs, methods, and functions, so if you say, for example, declare a function with the capital letter that function could be easily invoked in the current package as well as in another package hence it makes it publicly available in code structure whereas if you declare a function with a small letter it would only be available to that particular package, hence making it more private and a bit secure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa484adc3ef57dbebad171f1194b08b9/href">https://medium.com/media/aa484adc3ef57dbebad171f1194b08b9/href</a></iframe><p>Hence, from the above example, you can see how functions can become private and public according to case sensitivity.</p><p>In terms of OOPs, encapsulation and abstraction are more than just data hiding and access specification it bring more features to the classes and interfaces, but in the case of Go, it just uses the lighter version of both concepts.</p><h4>Inheritance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*IG4MvVVrjeko_8-FN0_ZqA.jpeg" /></figure><p>In brief, <a href="https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)#:~:text=Inheritance%20allows%20programmers%20to%20create,via%20public%20classes%20and%20interfaces.">inheritance</a> means to create new classes(subclasses or derived classes) from existing base(parent) classes and achieve code reusability. In Go, there is no such thing as inheritance but there is <strong>composition </strong>to achieve structure inheritance via <strong>struct-embedding </strong>means to embed fields of one struct to another struct. You can get to know more about struct-embedding by this link: <a href="https://gobyexample.com/struct-embedding">https://gobyexample.com/struct-embedding</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6559bcb3470f25d966a237a46489e4f9/href">https://medium.com/media/6559bcb3470f25d966a237a46489e4f9/href</a></iframe><p>Go only supports composition if we say it in terms of inheritance. While inheritance is more than just composition as people who are having experience in OOPs languages like JAVA, C++, etc.</p><h4>Polymorphism</h4><p><a href="https://en.wikipedia.org/wiki/Polymorphism_(computer_science)">Polymorphism</a> is the oop concept in which an object is capable of molding into multiple forms just like three spiderman’s in our case from a different dimension with different forms but the entity is the same.</p><p>In Go, we can achieve polymorphism via implementing <a href="https://gobyexample.com/interfaces"><strong>interfaces</strong></a><strong> </strong>in Go<strong>. </strong>Interfaces work as a collection of methods. Let’s get more familiar with an example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64d18246c08ec95339d9d2fd40006696/href">https://medium.com/media/64d18246c08ec95339d9d2fd40006696/href</a></iframe><p>Hence, in the above example, as you can see the Developer struct implements the Tasks interface by defining methods like BugFix and Improvement. I have written this example because we developers are much more friendly with these terms in our days while getting assigned different versions of tasks like bugfix, improvements, hotfix, etc.</p><h4>Enums</h4><p><a href="https://en.wikipedia.org/wiki/Enumerated_type">Enum</a> is a special data type with enumerated data which consists of a set of elements. Mostly the enumerated data is of constant type in many languages.<br>In the case of Go, we can create enums and define constant variables accordingly by declaring <strong>iota</strong> to the first variable in a series of it. The iota keyword represents the integer constant from zero.</p><pre>const (<br>     Java = iota<br>     Go<br>     Javascript<br>     Rust<br>)</pre><pre>Output: 0 1 2 3</pre><p>There are some more examples with which we can get to know more about how iota works differently with several ways of initialization.</p><pre>const (<br>     Java = iota<br>     Go<br>     _<br>     Rust<br>)</pre><pre>Output: 0 1 3</pre><p>Above, as you can see the _ skips the value in the enum counter</p><pre>const (<br>     Java = iota<br>     Go<br>)</pre><pre>const (<br>     Rust = iota<br>     Javascript<br>)</pre><pre>Output1: 0 1<br>Output2: 0 1</pre><p>Above, as you can see if you define the different enumerated typed constants they will have their own increment values starting from zero.</p><p>So, that’s it about OOPs in Go. In an upcoming article, I will write that how we can achieve functional programming in Go, and also I will be coming up with system design principles.</p><p>Stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6568f7b76f5f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-achieve-principles-of-oops-in-go-6568f7b76f5f">How to Achieve Principles of OOPs in Go</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Fundamentals of Pointers in Go]]></title>
            <link>https://medium.com/better-programming/pointers-in-go-9aa5c0682a?source=rss-d2d76b301ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/9aa5c0682a</guid>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Nikhil Vaidyar]]></dc:creator>
            <pubDate>Fri, 25 Feb 2022 06:28:30 GMT</pubDate>
            <atom:updated>2022-04-18T14:48:22.548Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding pointer types and how to use them in data structures</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kIk6j7tyMSzHtwYrnagULA.jpeg" /><figcaption>`A “Marketplatz cafe” by <a href="https://unsplash.com/@mparzuchowski">Michael Parzuchowsk</a>i on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>Suppose, you have plans with your friends for a get-together at everyone’s favorite cafe. And all y’all have reached the location and are at the cafe’s door. But it reads: “Sorry we have moved to this XYZ location”. So, as it’s your favorite cafe you will go to the new address. That’s how pointers are. A bit like the sign on the cafe’s door that directs you to a different address/location.</p><h4>So, what are pointers and why do we need to use them?</h4><p>A pointer is a variable that stores a memory address. In simple terms, it stores the value in your computer memory. Though later we can access it using pointer address.</p><p>We use pointers when we want to pass a variable by reference to some function and also for pointing out arrays, structs, interfaces, functions, etc.</p><p>Languages like C often face some crashes and security vulnerabilities when using pointers. Go uses pointers but with memory safety. So we are in good hands now.</p><p>Well, that’s a brief about pointers. So let’s get to know more about pointers in go.</p><h3>Ampersand(&amp;) and Asterisk(*)</h3><p>The address operator (&amp;) simply determines the address of a variable in memory. Suppose, you assign some value to a variable. Your computer will store that value in your memory address(RAM) as a hexadecimal number.</p><pre>value := 901<br>fmt.Println(&amp;value)<br>//Prints -&gt; 0xc000018030</pre><p>When we need to dereference the value of the pointer, we can use the (*) operator to dereference the pointer variable and retrieve its value. Okay, so let’s get more familiar with a good example:</p><pre>value := 65<br>memoryAdd := &amp;value<br>fmt.Println(&quot;Value:&quot;, value) // 65<br>fmt.Println(&quot;Memory address:&quot;, &amp;memoryAdd) // 0xc000100018 <br>fmt.Println(&quot;Dereferencing using pointer:&quot;, *memoryAdd) // 65</pre><p>We can also update the original value with the dereferencing using the pointer operator. Here’s the example:</p><pre>var name string = &quot;John&quot;<br>var pointer *string = &amp;name</pre><pre>fmt.Println(&quot;Name =&quot;, name) //John<br>fmt.Println(&quot;pointer =&quot;, pointer) //0xc000010230<br>fmt.Println(&quot;*pointer =&quot;, *pointer) //John</pre><pre>*pointer = &quot;Robert Downy Junior&quot;</pre><pre>fmt.Println(&quot;*pointer =&quot;, *pointer) //Robert Downy Jr<br>fmt.Println(&quot;name =&quot;, name) //Robert Downy Jr</pre><p>In the above example, the variable defined as the name has a value John that we want to dereference with a pointer variable using (*) before the variable.</p><p>So, in our case pointer variable assigned to a new value which is Robert Downy Jr can change the value of the pointer which is referenced to the memory address. And guess what? It also changes the value of the variable name itself. That’s the beauty of dereferencing — it can be confusing and very reusable at the very same time.</p><h3>Pointer Types</h3><p>In simpler terms, pointer type is a pointer variable initialized before a data type. Here’s an example:</p><pre>types := 881<br>address := &amp;types<br>fmt.Printf(&quot;Address is a %T\n&quot;, address) // Address is a *int</pre><p>The *int denotes that the type is a pointer. If the pointer type is of *int, it can point to any other variables of the same type.</p><p>In the above example of dereferencing, we can see that first, we have defined a variable name with a value of *string, and we have dereferenced the pointer value with another string value — and it also updates the original variable name with another string value.</p><p>The major advantage of using pointer type in Go is that it avoids unsafe operations like updating or manipulating any value. Hence, Go is also a strictly typed language.</p><blockquote><em>Note: In C language type, a memory address can hold the different pointer type, whereas in Go, it will throw an error. Check this link for reference: </em><a href="https://go.dev/play/p/PFBD3_5BnLP">https://go.dev/play/p/PFBD3_5BnLP</a></blockquote><p>What if we define pointers using data structures in go which are like arrays, slices, maps, etc., and what go compiler will return in that time? So, let’s get to know more about pointers in a bit deep.</p><h3>How pointers are in nature with data structures</h3><p>To start off, let’s get familiar more with pointers with the use of data structures in Go</p><h4>Using pointers in structs</h4><p>This pointer points to the address of the memory block which stores the data in a struct. Here’s an example:</p><pre>type Person struct {<br> name    string<br> age     int<br> canSing bool<br>}</pre><pre>func main() {<br> john := &amp;Person{<br>  name:    &quot;John&quot;,<br>  age:     22,<br>  canSing: false,<br> }</pre><pre>fmt.Printf(&quot;%+v\n&quot;, john) // &amp;{name:John age:22 canSing:false}<br>}</pre><p>As you can see here, we have defined a struct called Person<em> </em>and after that, we defined the values via initializing a variable called john using the address operator before struct.</p><p>The output for the above example will return the values of the defined variable with the address operator ahead.</p><pre>fmt.Printf(&quot;%+v\n&quot;, *john) // {name:John age:22 canSing:false}<br>john.canSing = true<br>fmt.Printf(&quot;%+v\n&quot;, *john) // {name:John age:22 canSing:true}</pre><p>Here, we can use the pointer operator to dereference the variable and also define the value in struct.</p><h4>Using pointers in arrays</h4><p>Arrays can be prefixed with the address operator to create a new pointer to an array. Arrays also provide automatic dereferencing. Here’s one example:</p><pre>person := &amp;[3]string{&quot;John&quot;, &quot;22&quot;, &quot;12-12-2021&quot;}<br>fmt.Println(person[0]) // John<br>fmt.Println(person[:2]) // [John 22]</pre><p>As we can see here, even in indexing or whether it is slicing, it automatically dereferences the returned value.</p><h4>Using pointers in maps</h4><p>Using pointers in maps is ideally not a good try as go uses pointers behind the scenes for some of the in-built collections. It’s fine if the key or a value in a map can be of a pointer type, but not for the whole map. It will act redundantly in nature.</p><h3>Pointer in functions</h3><p>In general, functions are a way to take inputs as an argument and give the desired output in such a way that solves a problem of any kind. So, when writing functions, we can define arguments as pass by value and pass by reference. Here’s a <a href="https://www.educative.io/edpresso/pass-by-value-vs-pass-by-reference">nice read for the same</a>:</p><blockquote>In pass by value, it creates a copy of the value which is sent to a function as formal argument, any changes to the function will only impact only the function’s variable, it will not update the value outside of the function scope.</blockquote><p>Here’s an example for better understanding:</p><pre>func main() {<br> var name string = &quot;Nikhil&quot;<br> fmt.Println(&quot;Name = &quot;, name) // Nikhil<br> changeName(name)<br> fmt.Println(&quot;Name = &quot;, name) // Nikhil<br>}</pre><pre>func changeName(name string) {<br> name = &quot;John&quot;<br> fmt.Println(&quot;Updated name = &quot;, name) // John<br>}</pre><p>In the above example, as we can see the value of the name is only updated when it is updated in changeName<em> </em>function, so the value of the name would be now different only for this function, as the values are function scoped.</p><p>In global and in outer function scope, it will act the same way as it was defined initially. But, what if we want to update the value from the function and it should also update or mutate the original value too. In this case, we can use pass-by-reference for that.</p><blockquote>In pass by reference, it updates the original value when the value is updated in a function call. Hence, in this case, it updates value while using pointer before the actual paramter and passing the arguments to function call by reference. Here’s an example for this:</blockquote><pre>func main() {<br> var name string = &quot;Nikhil&quot;<br> fmt.Println(&quot;Original name =&quot;, name) // Nikhil<br> changeName(&amp;name)<br> fmt.Println(&quot;Original name is now changed to =&quot;, name) // John<br>}</pre><pre>func changeName(name *string) {<br> *name = &quot;John&quot;<br> fmt.Println(&quot;Updated name =&quot;, *name) //John<br>}</pre><h3>Pointers in methods</h3><p>In methods, there is one slight difference from the functions, In this, we have a receiver as an argument in the method declaration.</p><p>Just like functions, methods behave the same for sending value as an argument as a pointer or not.</p><p>In the case of methods, if we want to send the value as a receiver, it will not be going to impact the original value. For example:</p><pre>type About struct {<br> name string<br> age  int<br>}</pre><pre>func main() {<br> var details About = About{name: &quot;Nikhil&quot;, age: 25}<br> fmt.Printf(&quot;%+v\n&quot;, details) // {name:Nikhil age:25}<br> details.UpdateDetails()<br> fmt.Printf(&quot;%+v\n&quot;, details) // {name:Nikhil age:25}<br>}</pre><pre>func (a About) UpdateDetails() {<br> a.age = 35<br> a.name = &quot;Antman&quot;<br> fmt.Printf(&quot;%+v\n&quot;, a) // {name:Antman age:35}<br>}</pre><p>In this example, I have used structs as it’s a user-defined type in Go. And it also supports methods on struct types. Hence, the receiver can be of struct or non-struct type.</p><p>Coming to our code, here we are defining a group of data in which there are two fields: name and age<em>. </em>We have also defined and invoked one method called UpdateDetails<em> </em>which actually just updates the value while using function receiver as an argument from formal parameter with struct type of About<em>.</em></p><p>As we have also defined the details variable with struct type of About<em> </em>to defined the values initially. Here, we can see the same expected result as we were seeing the same when we were using <em>pass-by-value</em> in function invocation.</p><p>What if we want to update the values as we were doing the same in <em>pass-by-reference, </em>we just need to add a pointer before the struct type to update the original value outside the method scope whether it is declared outside the main function also. So, here’s one example for that too:</p><pre>type About struct {<br> name string<br> age  int<br>}</pre><pre>func main() {<br> var details About = About{name: &quot;Nikhil&quot;, age: 25}<br> fmt.Printf(&quot;%+v\n&quot;, details)<br> details.UpdateDetails()<br> fmt.Printf(&quot;%+v\n&quot;, details)<br>}</pre><pre>func (a *About) UpdateDetails() {<br> a.age = 22<br> a.name = &quot;John&quot;<br> fmt.Printf(&quot;%+v\n&quot;, *a)<br>}</pre><p>So, that’s how pointers work in methods and it’s quite easy right.</p><h3>Nils in pointers</h3><p>Suppose there’s a case where you have initialized a pointer but you have not defined or assigned it. So, what happens in Go is that all variables have zero values. So, if just initialized an array, slice, pointer it will be having zero value, so Go treats this zero value as nil means “nothing is initialized”.</p><p>Let’s take an example to check how it actually happens. So, I will be taking one of the examples which I have explained above in functions using pointers”</p><pre>type Person struct {<br> name string<br>}</pre><pre>func main() {<br> var name *Person<br> fmt.Printf(&quot;%+v\n&quot;, name)<br> changeName(name)<br> fmt.Printf(&quot;%+v\n&quot;, name)<br>}</pre><pre>func changeName(name *Person) {<br> name = &amp;Person{name: &quot;Nikhil&quot;}<br> if name == nil {<br>  fmt.Println(&quot;Name is nil&quot;)<br>  return<br> }<br> fmt.Printf(&quot;%+v\n&quot;, name)<br>}</pre><p>Instead of assigning the variable name<em>, </em>I have just initialized it just to check what actually happens, so while running it, I got this error: <a href="https://go.dev/play/p/NEXaSROifVs">https://go.dev/play/p/1MFlmIqSGwM</a></p><p>The error says <strong>runtime error: invalid memory address.</strong> So it proves the point that if we just initialized a pointer variable, Go treats it as a zero value and zero values are nil in nature. Though, we can add an error handling check for nil pointers.</p><pre>func changeName(name *string) {<br> if name == nil {<br>  fmt.Println(&quot;Name is nil&quot;)<br>  return<br> }<br> fmt.Printf(&quot;%+v\n&quot;, name)<br>}</pre><p>Now, if we want to update the value of the pointer via assigning it to a name<em> </em>variable, we can do so by:</p><pre>func main() {<br> var name *Person<br> fmt.Printf(&quot;%+v\n&quot;, name) // &lt;nil&gt;<br> changeName(name)<br> fmt.Printf(&quot;%+v\n&quot;, name) // &lt;nil&gt;<br>}</pre><pre>func changeName(name *Person) {<br> name = &amp;Person{name: &quot;Nikhil&quot;}<br> if name == nil {<br>  fmt.Println(&quot;Name is nil&quot;)<br>  return<br> }<br> fmt.Printf(&quot;%+v\n&quot;, *name) // {name:Nikhil}<br>}</pre><p>Whenever we are working with pointers we should be very careful as it can panic the program. To avoid panicking, we need to check if pointers are not nil in nature.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9aa5c0682a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/pointers-in-go-9aa5c0682a">The Fundamentals of Pointers in Go</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang Basics: Maps]]></title>
            <link>https://nikhilvaidyar.medium.com/golang-basics-maps-79bb9a3d90a7?source=rss-d2d76b301ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/79bb9a3d90a7</guid>
            <category><![CDATA[hash-table]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[concept]]></category>
            <category><![CDATA[go-programming]]></category>
            <dc:creator><![CDATA[Nikhil Vaidyar]]></dc:creator>
            <pubDate>Sun, 04 Jul 2021 17:01:11 GMT</pubDate>
            <atom:updated>2021-07-04T17:01:11.939Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Not actually a physical form of maps" src="https://cdn-images-1.medium.com/max/1024/1*KefUpgflMMiOGSjcNHI12g.jpeg" /><figcaption>Not a physical form of maps</figcaption></figure><p>Hey everyone, Today, I will talk about the concept of maps in Go, which is used to store data in key values pairs. A brief about the Go maps is that built-in map types are implemented by a common data structure, hash table.</p><h3>What is Hash Table?</h3><blockquote>A hash table is a data structure where data is stored in an associative manner. The data mapped to array positions by a hash functions that generates a unique value from each key.</blockquote><figure><img alt="Hash Table representation" src="https://cdn-images-1.medium.com/max/1024/1*PG_O25srs_O_hdQqc-3Mbw.png" /><figcaption>Hash Table representation</figcaption></figure><p>The major advantage of hash tables that they are efficient. The access time for an element is on average <strong>O(1), </strong>so it offers faster lookups, adds, and deletes<strong>. </strong>The hash function generates and addresses from the key. This process of mapping keys to the appropriate location is called <strong>hashing.</strong></p><p>Okay, enough explanation of hash table data structure. Coming back to our topic. So, map data type in Go means it maps keys to values. It maps keys to values and stores the data in Go.</p><h3>Maps in action</h3><p>Here’s how a Go to map data type looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*65N8nmB8AGobmZ1GaFQtxw.png" /><figcaption>Map signature in Go</figcaption></figure><p>Map types are just reference types like slices or pointers. An empty map acts as a nil data type in Go, whereas if you just declared a nil map, it will return an empty map like this:</p><pre>var m map[string]int<br>// map[]</pre><p>If we try to write to a nil map, it will cause the runtime panic error. Here’s the screenshot of that:</p><figure><img alt="Runtime panic error of nil maps in Go" src="https://cdn-images-1.medium.com/max/1024/1*5hMQj9MwJzlRMgV2iwxbWw.png" /><figcaption>Runtime panic error of nil maps in Go</figcaption></figure><p>You can also check this out just go to this link: <a href="https://play.golang.org/"><em>https://play.golang.org/</em></a><em>. Go provides a playground to run, test, or multiple operations, etc.</em></p><p>In this case, as we have declared a map using the var keyword, we can use a built-in function <strong>make </strong>to pass this runtime panic error. While using this function it allocates and initializes a hash map data structure and returns a map value that points to it.</p><pre>var m map[string]int<br>m = make(map[string]int)<br>m[&quot;age&quot;] = 24<br>fmt.Println(m) // map[age:24]</pre><p>Hence, we can also initialize a map using map literal.</p><pre>m := map[string]string{&quot;name&quot;: &quot;John&quot;, &quot;age&quot;: &quot;24&quot;, &quot;sex&quot;: &quot;Male&quot;}<br>// map[age:24 name:John sex:Male]</pre><p>We can also initialize an empty array with map literals, which is identical to use the built-in make function.</p><p>To iterate over key-value pairs in the map, we can use the range keyword which we have discussed in our previous blog of <a href="https://medium.com/@nikhilvaidyar1997/golang-basics-array-and-slices-9652dfd271dc"><em>Array and Slices</em></a></p><figure><img alt="Range keyword in Go map" src="https://cdn-images-1.medium.com/max/1024/1*4kka0jY6PWeuiHCxAJrk5A.png" /><figcaption>Range keyword in Go map</figcaption></figure><p>There are two other built-in functions that Go provides us to execute more operations in our code, we can use <strong>len</strong> to check the map length, and also if we want to delete some of the existing keys, we can just implement the delete function while passing the values in arguments. Moreover, the delete function doesn’t return anything and will do nothing if the specified key doesn’t exist. Hence, I am trying these two built-in functions for the above mapData map.</p><pre>len(mapData) // 3<br>delete(mapData, &quot;name&quot;) // map[age:812 location:Titan]</pre><h3>Concurrency in maps</h3><p>According to Go, maps are not safe for concurrent use, because if we need to read from and write to a map from concurrently executing goroutines, we need to perform this operation in a more synchronized manner. Thus, Go provides us a common way to handle and secure maps using sync.RWMutex.</p><h4>sync.RWMutex</h4><p>It’s a reader/writer mutual exclusion lock. It contains filtered data. This is a deep topic which I will explain thoroughly in my upcoming Golang series blogs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79bb9a3d90a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang Basics: Array and Slices]]></title>
            <link>https://nikhilvaidyar.medium.com/golang-basics-array-and-slices-9652dfd271dc?source=rss-d2d76b301ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/9652dfd271dc</guid>
            <category><![CDATA[basics]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[slice]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nikhil Vaidyar]]></dc:creator>
            <pubDate>Sun, 20 Jun 2021 14:04:49 GMT</pubDate>
            <atom:updated>2021-06-20T14:04:49.953Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TgkaPc08v4_rTl2Nbzzk_g.jpeg" /></figure><blockquote>Hey everyone, Today, I will talk about some basic concepts of Go in which we discuss the building block data structure, which is arrays and slices.</blockquote><p>We all are accustomed to knowing how arrays work, and we also use this data structure in most of our projects.</p><p>Hence, I will rephrase it once again to understand arrays in Golang.</p><h3>Arrays in Go</h3><p>Arrays are fixed-size elements and have contiguous memory, and they cannot shrink and grow in size. Some advantages of using arrays are that they have random access, and they are cache-friendly. Here’s a simple representation of the array in Go.</p><figure><img alt="Representation of an array in Go" src="https://cdn-images-1.medium.com/max/1024/1*vAlf57u4B2MMKbQ-Bb0Zxw.png" /><figcaption>Representation of an array in Go</figcaption></figure><pre>var myArr [4]int<br>myArr[2] = 33<br>newArr := myArr<br>// newArr = 33</pre><p>n Golang, <strong>variables</strong> are explicitly declared and used by the compiler.<br>The in-memory representation of [4]int in a sequenced manner:</p><figure><img alt="Pictorial representation of an array" src="https://cdn-images-1.medium.com/max/1024/1*7NFGoT0CTqxCB9qhjr3uzw.png" /><figcaption>Pictorial representation of an array</figcaption></figure><p>An array variable denotes the entire array, which means assigning an array variable will create a copy of its content.</p><p>It can also be declared as:</p><pre>values := [4]string{&#39;John&#39;, &#39;Bob&#39;, &#39;Kyle&#39;, &#39;Jack&#39;}<br>values := [...]string{&#39;Austin&#39;, &#39;John&#39;}</pre><p><strong>You must be thinking what those three dots are in an array […]?</strong></p><p>Okay, there is a slight difference between []string and […]string, []string is nothing but a string array. The […]string is a parameter syntax that makes it a variadic parameter; it will accept 0 and more string values and reference them as a slice. So regardless of giving the element count in an array, you can just annotate like this […] to make it more dynamic.</p><p>The built-in function <strong>len</strong> usually just returns the length of the array. Talking about <strong>loops </strong>we use it to iterate over an array of single and multi-dimensional arrays, although there is another controlled way that Go provides us to serve, there is a keyword called <strong>range </strong>which iterates as the same as for loop but in the hand, it does more elegantly and cleanly. Range with maps works efficiently.</p><p><strong>Some limitations of using arrays in Go:</strong></p><ul><li>Arrays in Go are not resizable and dynamic.</li><li>Passing an array to a function as a parameter, you passing the copy of an array, which means that any changes you will be doing inside the function will be lost after the function gets executed.</li><li>Passing a large array to a function can be pretty slow. To overcome this inefficiency, Go has a dynamic array called slices, by which we can overcome all these limitations.</li></ul><h3>Slices in Go</h3><p>In simple words, slices are dynamic arrays. They provide more flexibility and efficiency over arrays.</p><ul><li>Slices are implemented using arrays internally, which means that Go uses an underlying array for each slice.</li><li>Slices are <strong>passed by reference</strong> to the functions, which means the memory address of the slice variable is passed. Any changes that you will make to the slice will not be lost after the function execution.</li><li>Passing a big slice is much faster than passing an extensive array to the function because Go will not have to copy the slice. It will just pass the memory address to the slice variable.</li></ul><p>A slice literal is declared exactly like a normal array in Go, only without the element count.</p><pre>myIntSlices := []int{12, 45, 89, 90}<br>myStringSlices := []string{&#39;John&#39;, &#39;Diana&#39;, &#39;Jess&#39;, &#39;Rachel&#39;}</pre><p>Slices can also be created by a built-in function called <strong>“make”.</strong></p><figure><img alt="Go (make) function signature" src="https://cdn-images-1.medium.com/max/1024/1*LDj1ecLzotKU_fqFVY_S2w.png" /><figcaption>Go (make) function signature</figcaption></figure><pre>randomSlice := make([]byte, 5, 5)<br>// randomSlice = []byte{0, 0, 0, 0, 0}</pre><p>It is optional to pass capacity in the make function. It’s just that by default, the capacity will take the length values.</p><h4>Internals of Slices</h4><p>The internals part of slices consists of a pointer to the array, length, and capacity.</p><figure><img alt="Internals of slices" src="https://cdn-images-1.medium.com/max/615/1*5YjwHKkbyYr5bkjmnjDfGg.png" /><figcaption>Internals of slices</figcaption></figure><p><strong>Length: </strong>It is the number of elements referred to by the slice.<br><strong>Capacity: </strong>It is the number of elements in an array.</p><p>Slices can also be formed by “re-slicing” an array or slice.</p><pre>items := []int{1, 2, 3, 4, 5}<br>items[1:3] // {2, 3}<br>items[2:] // {3, 4, 5}<br>items[:3] // {1, 2, 3}<br>items[:] // {1, 2, 3, 4, 5</pre><blockquote>Note: Ever wonder what’s this “<strong>:”</strong> notation means, it means to create a new slice that references an existing slice.</blockquote><p>This way it creates a new slice that points to the original slice. If modifying the newly created array with the original array or slice becomes efficient. Hence, it is mutable in nature.</p><p>A slice cannot be grown beyond its capacity. Hence it will end in runtime panic or indexing out of the bounds of a slice.</p><h4><strong>Growing nature of slices</strong></h4><p><strong>Copy:</strong> This function supports copying between slices of different lengths. The in-built copy function copies the minimum len(s2) and len(s1) elements.</p><figure><img alt="Go (copy) function signature" src="https://cdn-images-1.medium.com/max/1024/1*Vq70R7Wext9iNSqh-y_y3Q.png" /><figcaption>Go (copy) function signature</figcaption></figure><blockquote><strong>Copy function copies the data from a source slice to the destination slice and returns the number of elements copied to the destination slice.</strong></blockquote><p>Here’s an example:</p><figure><img alt="Go — copy function example" src="https://cdn-images-1.medium.com/max/1024/1*NTJSQMGspwca0JQGJJ-h5g.png" /><figcaption>Go — copy function example</figcaption></figure><p><strong>Append: </strong>In simple terms, you already know it means to add something. But, in Go, the append function means to append the elements for, say, <strong>x</strong> elements to the end of the slice <strong>s</strong>, and it grows the slice if the capacity is needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1mXblcRrboHF6HLUjBWU3g.png" /><figcaption>Go (append) function signature</figcaption></figure><p>Here’s an example for the append function in practice:</p><figure><img alt="Go — append function example" src="https://cdn-images-1.medium.com/max/1024/1*Cex2BLMK4sIvNSbeqSj0Ow.png" /><figcaption>Go — append function example</figcaption></figure><p>Functions like append provide total control of the way the slice is grown. Go shows us that to grow a slice, we will need to implement an append function and not refer to an index that does not exist. It could end up giving an error message: <strong>panic: runtime error: index out of range.</strong></p><p>I think you probably got an idea of how to implement the arrays and slices, when and why?</p><p>Thanks for reading this far. If there are any blunders in this post, feel free to suggest possible changes required to make this post more informative. It was just brief information to get familiar with the go concepts. Meanwhile, you can reach out to the official Go blog website for more: <a href="https://blog.golang.org/slices-intro">https://blog.golang.org/</a></p><h4>Links which I referred to:</h4><blockquote><a href="https://blog.golang.org/slices-intro">https://blog.golang.org/slices-intro</a><br>If you want to know more about slices, you can check out this blog too: <a href="https://blog.golang.org/slices">https://blog.golang.org/slices</a></blockquote><h4>Books which I referred to:</h4><blockquote><strong>Mastering Go</strong> by Mihalis Tsoukalos<br><strong>The Go Programming Languag</strong>e by Alan A. A. Donovan &amp; Brian W. Kernighan</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9652dfd271dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Novice adolescent re-create some “ART”]]></title>
            <link>https://nikhilvaidyar.medium.com/novice-adolescent-re-create-some-art-7864abe8b61a?source=rss-d2d76b301ce------2</link>
            <guid isPermaLink="false">https://medium.com/p/7864abe8b61a</guid>
            <category><![CDATA[passion]]></category>
            <category><![CDATA[art]]></category>
            <category><![CDATA[paint]]></category>
            <category><![CDATA[love]]></category>
            <category><![CDATA[colors]]></category>
            <dc:creator><![CDATA[Nikhil Vaidyar]]></dc:creator>
            <pubDate>Wed, 09 Oct 2019 21:30:18 GMT</pubDate>
            <atom:updated>2019-10-09T21:30:18.233Z</atom:updated>
            <content:encoded><![CDATA[<p>First of all it is re-created by me in my own version to give a chance to my painting talent(P.S. Painting with Jane). It’s been a long time since I have been drawing and painting. I rather love more to paint. In short I like to give colors to something which is non-living to make it real, like it’s responding to us.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p><strong><em>Alluring lady with Umbrella</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/0*3wXki33JYpCfa7XO" /><figcaption>Umbrella and Red Dress</figcaption></figure><p>Talking about this portrait, I only spend 2 hours just to make it. I made it with some broken brushes because I couldn’t afford a good soft brushes which gives a more detailing and more good at finishing. Until though I never lose, I just want to paint, these type of silly obstacle is just absurd. About this lady, holding an red umbrella on such a rainy day, makes her dress and her set of hair from behind make it more charming and lovely. Alone this lady, thinking about something like her career, work and and all other things which are out of topic, but then she realized that she’s is freed, she can enjoy this weather, by seeing all the beautiful surrounding around her and to forget all the past, she’s just got to know from nature reality that she is missing something beautiful that may not come back in her life. It shows that a human whether she is a man or a woman, the nature can relieve or give a path to them. We just have to think different.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p><strong><em>A FRAMEWORK WITH PANE</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*XLRJC-VBA0mJW1J1" /><figcaption>A window pane</figcaption></figure><p>I don’t know how but this window have something which makes me to gawk at. I love to see it’s detailing. I seriously doubt myself that how i re-created this, but somehow I paint this when there is actually raining outside which giving me chills to draw it more accurately. When I learn that how to draw drops I got excited I tried and tried and then came up with this. When I complete it, I just halt for moment and then I smiled at my painting that I actually drew this. I know it’s not a big famous painting, but at that very moment, it somehow take me to other place at which I still wanna be. It shows that glass not always reflects it also gives a chance to see something else.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p><strong><em>Vintage Lamp in dense trees</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*20hWQ1jwX7XcyfhO" /><figcaption>Rusty Lamp</figcaption></figure><p>Still this painting is re-created by me. I know it’s pretty messed up, but the way that vintage lamp scatters the light on that summer night, creates a moment to remember the scene. The way the light scatters on the leaves, branches,insects, and all around wherever the light can go creates a beautiful image which gives the chills in that clear summer-breezy night. Last night, I dreamed about this painting in which I am holding the hand of my soulmate and I walking along with her and then I saw this graceful moment at which how the light spread all through the way. It shows that light is complete with darkness.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7864abe8b61a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>