<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[GoTech With Alissa]]></title><description><![CDATA[GoTech With Alissa]]></description><link>https://blog.gotechwithalissa.com</link><generator>RSS for Node</generator><lastBuildDate>Wed, 22 Apr 2026 05:57:55 GMT</lastBuildDate><atom:link href="https://blog.gotechwithalissa.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Connecting to SQL Database with Go]]></title><description><![CDATA[The HTML and text templates, discussed in my previous few blog posts, are two of the many packages that become powerful tools when working with large datasets. Henceforth, my next series of blog posts]]></description><link>https://blog.gotechwithalissa.com/connecting-to-sql-database-with-go</link><guid isPermaLink="true">https://blog.gotechwithalissa.com/connecting-to-sql-database-with-go</guid><category><![CDATA[Go Language]]></category><category><![CDATA[golang]]></category><category><![CDATA[SQL]]></category><category><![CDATA[SQL Server]]></category><category><![CDATA[Databases]]></category><dc:creator><![CDATA[Alissa Lozhkin]]></dc:creator><pubDate>Tue, 21 Apr 2026 12:16:21 GMT</pubDate><content:encoded><![CDATA[<p>The HTML and text templates, discussed in my <a href="https://alissalozhkin.hashnode.dev/introduction-to-go-templates">previous few blog posts</a>, are two of the many packages that become powerful tools when working with large datasets. Henceforth, my next series of blog posts will focus on working with SQL databases in Go. This blog post will go through the steps on how to connect to a SQL database.</p>
<p>Before writing the code, we need to import the <code>database/sql</code> package. This package must be used in conjunction with a SQL driver. In this tutorial, I will be connecting to SQL Server so <code>github.com/microsoft/go-mssqldb</code> will be imported. More SQL drivers can be found <a href="https://go.dev/wiki/SQLDrivers">here</a> and each can be installed with the <code>go get</code> command. I've also imported <code>fmt</code> for printing purposes:</p>
<pre><code class="language-go">import (
    "fmt",
    "database/sql",
    _ "github.com/microsoft/go-mssqldb"
)
</code></pre>
<p>Notice that I put the blank identifier, <code>_</code>, before the driver package name. This indicates that the imported package will not be used in the code itself. We import the driver so that it can be registered with the imported <code>sql</code> package. Note that when assigning an alias to an imported package in Go, the alias name comes before the imported package name.</p>
<p>Before connecting to any database, you need to create a connection string which usually requires the following credentials: the database server, name, username, and password.</p>
<pre><code class="language-go">func main() {

    connString := fmt.Sprintf("server=%s;user id=%s;
        password=%s;database=%s;Integrated Security=false;                                                                                            TrustedServerCertificate=True", server, user, password, db_name)

}
</code></pre>
<p>The next thing to do is to open the connection with the <code>sql</code> package we imported:</p>
<pre><code class="language-go">connection, error := sql.Open("mssql", connString)
if err != nil {
    fmt.Println("Could not connect to the database)
    panic(err)
}
</code></pre>
<p>The <code>connection</code> variable declared above is of type <code>*sql.db</code> as it points to a SQL connection.</p>
<p>After opening the connection, we can verify it and then close it. The <code>defer</code> keyword ensures that the database connection is closed regardless of how the function terminates (with or without error):</p>
<pre><code class="language-go">error := db.Ping()
if err != nil {
    fmt.Println("Could not verify connection to the database)
    panic(err)
}

defer connection.close()
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Templates: Introduction to HTML Templates]]></title><description><![CDATA[There are many scenarios in which we want to create templates suitable for web applications. It is possible to write HTML templates dynamically using the text/template package, however using html/template makes your HTML templates injection-safe as i...]]></description><link>https://blog.gotechwithalissa.com/templates-introduction-to-html-templates</link><guid isPermaLink="true">https://blog.gotechwithalissa.com/templates-introduction-to-html-templates</guid><category><![CDATA[HTML templates in Go]]></category><category><![CDATA[golang]]></category><dc:creator><![CDATA[Alissa Lozhkin]]></dc:creator><pubDate>Thu, 31 Jul 2025 20:43:03 GMT</pubDate><content:encoded><![CDATA[<p>There are many scenarios in which we want to create templates suitable for web applications. It is possible to write HTML templates dynamically using the <code>text/template</code> package, however using <code>html/template</code> makes your HTML templates injection-safe as it automatically escapes HTML characters that are found in the input. For example, if the input contains characters such as <code>&lt;</code>, <code>&gt;</code>, or <code>&amp;</code>, the <code>html/template</code> package will convert these characters to <code>&amp;lt;</code>, <code>&amp;gt;</code>, and <code>&amp;amp;</code> respectively so that they don’t interfere with the overall HTML structure. In most cases, the input for templates come from unknown sources, and so <code>html/template</code> should be used to produce HTML templates.</p>
<p>We begin with the same code in <code>main.go</code> as in my <a target="_blank" href="https://alissalozhkin.hashnode.dev/templates-using-actions-functions-and-custom-functions">previous blog post</a>:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"html/template"</span>
    <span class="hljs-string">"os"</span>
    <span class="hljs-string">"strings"</span>
)

<span class="hljs-keyword">type</span> Person <span class="hljs-keyword">struct</span> {
    Name       <span class="hljs-keyword">string</span>
    Age        <span class="hljs-keyword">int</span>
    Employed   <span class="hljs-keyword">bool</span>
    Occupation <span class="hljs-keyword">string</span>
    Interests  []<span class="hljs-keyword">string</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sub</span><span class="hljs-params">(i <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
    <span class="hljs-keyword">return</span> i - <span class="hljs-number">1</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    people := []Person{
        {
            Name:       <span class="hljs-string">"Bob"</span>,
            Age:        <span class="hljs-number">42</span>,
            Employed:   <span class="hljs-literal">true</span>,
            Occupation: <span class="hljs-string">"Doctor"</span>,
            Interests:  []<span class="hljs-keyword">string</span>{<span class="hljs-string">"Reading"</span>, <span class="hljs-string">"Swimming"</span>},
        },
        {
            Name:       <span class="hljs-string">"Jessica"</span>,
            Age:        <span class="hljs-number">22</span>,
            Employed:   <span class="hljs-literal">false</span>,
            Occupation: <span class="hljs-string">""</span>,
            Interests:  []<span class="hljs-keyword">string</span>{<span class="hljs-string">"Piano"</span>, <span class="hljs-string">"Baking"</span>},
        },
        {
            Name:       <span class="hljs-string">"Ben"</span>,
            Age:        <span class="hljs-number">23</span>,
            Employed:   <span class="hljs-literal">false</span>,
            Occupation: <span class="hljs-string">""</span>,
            Interests:  []<span class="hljs-keyword">string</span>{<span class="hljs-string">"Music"</span>, <span class="hljs-string">"Running"</span>},
        },
    }
    tmplFile := <span class="hljs-string">"demo_html.tmpl"</span>
    fMap := template.FuncMap{
        <span class="hljs-string">"sub"</span>:  sub,
        <span class="hljs-string">"join"</span>: strings.Join,
    }
    tmpl, err := template.New(tmplFile).Funcs(fMap).ParseFiles(tmplFile)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-built_in">panic</span>(err)
    }
    file, err := os.Create(<span class="hljs-string">"layout.html"</span>)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-built_in">panic</span>(err)
    }
    err = tmpl.Execute(file, people)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-built_in">panic</span>(err)
    }
}
</code></pre>
<p>Note that I created a new template file <code>demo_html.tmpl</code>. Also, instead of outputting the template to the terminal, I chose to write it to a file called <code>layout.html</code>.</p>
<p>In <code>demo_html.tmpl</code>, we write the following code:</p>
<pre><code class="lang-go">{{ <span class="hljs-keyword">range</span> . }}

&lt;h1&gt; Name: {{.Name}} &lt;/h1&gt;
&lt;ul&gt;
&lt;li&gt; Age: {{.Age}} &lt;/li&gt;
&lt;li&gt; Occupation: {{ <span class="hljs-keyword">if</span> .Employed }}{{ .Occupation }}{{ <span class="hljs-keyword">else</span> }}Unemployed{{end}} &lt;/li&gt;
&lt;li&gt; Interests: {{ join .Interests <span class="hljs-string">" &amp; "</span> }} &lt;/li&gt;
&lt;/ul&gt;

{{ end }}
</code></pre>
<p>After saving this file and running <code>go run main.go</code>, opening <code>layout.html</code> reveals the following:</p>
<pre><code class="lang-go">&lt;h1&gt; Name: Bob &lt;/h1&gt;
&lt;ul&gt;
&lt;li&gt; Age: <span class="hljs-number">42</span> &lt;/li&gt;
&lt;li&gt; Occupation: Doctor &lt;/li&gt;
&lt;li&gt; Interests: Reading &amp;amp; Swimming &lt;/li&gt;
&lt;/ul&gt;


&lt;h1&gt; Name: Jessica &lt;/h1&gt;
&lt;ul&gt;
&lt;li&gt; Age: <span class="hljs-number">22</span> &lt;/li&gt;
&lt;li&gt; Occupation: Unemployed &lt;/li&gt;
&lt;li&gt; Interests: Piano &amp;amp; Baking &lt;/li&gt;
&lt;/ul&gt;


&lt;h1&gt; Name: Ben &lt;/h1&gt;
&lt;ul&gt;
&lt;li&gt; Age: <span class="hljs-number">23</span> &lt;/li&gt;
&lt;li&gt; Occupation: Unemployed &lt;/li&gt;
&lt;li&gt; Interests: Music &amp;amp; Running &lt;/li&gt;
&lt;/ul&gt;
</code></pre>
<p>You can see in <code>layout.html</code> that the <code>&amp;</code> characters are escaped by <code>html/template</code> package. Running <code>layout.html</code> will give the following on a web browser:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1753993915982/685e5384-0486-43ab-b44a-ecf3b181aeba.png" alt class="image--center mx-auto" /></p>
]]></content:encoded></item><item><title><![CDATA[Templates: Using Actions, Functions, and Custom Functions]]></title><description><![CDATA[My previous blog post introduced the feature of actions in templates. Another very similar feature is a function, which can be used together with an action to perform additional operations on the data. For example, {{ range }} is an action as it cont...]]></description><link>https://blog.gotechwithalissa.com/templates-using-actions-functions-and-custom-functions</link><guid isPermaLink="true">https://blog.gotechwithalissa.com/templates-using-actions-functions-and-custom-functions</guid><category><![CDATA[template functions in Go]]></category><category><![CDATA[template custom functions in Go]]></category><category><![CDATA[golang]]></category><category><![CDATA[templates in Go]]></category><category><![CDATA[Template actions in Go]]></category><dc:creator><![CDATA[Alissa Lozhkin]]></dc:creator><pubDate>Mon, 28 Jul 2025 15:38:48 GMT</pubDate><content:encoded><![CDATA[<p><a target="_blank" href="https://alissalozhkin.hashnode.dev/how-to-create-plaintext-reports-in-go-using-templates-with-loops-and-conditionals">My previous blog post</a> introduced the feature of actions in templates. Another very similar feature is a function, which can be used together with an action to perform additional operations on the data. For example, <code>{{ range }}</code> is an action as it contributes to the overall structure of the template, whereas <code>{{ len }}</code> is a function as it performs a calculation. In this blog post, I will first demo how to use actions and functions together. I will then go over how to use custom functions in templates. We start with the following code in <code>main.go</code>:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"os"</span>
    <span class="hljs-string">"text/template"</span>
    <span class="hljs-string">"strings"</span>
)

<span class="hljs-keyword">type</span> Person <span class="hljs-keyword">struct</span> {
    Name       <span class="hljs-keyword">string</span>
    Age        <span class="hljs-keyword">int</span>
    Employed   <span class="hljs-keyword">bool</span>
    Occupation <span class="hljs-keyword">string</span>
    Interests  []<span class="hljs-keyword">string</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    people := []Person{
        {
            Name:       <span class="hljs-string">"Bob"</span>,
            Age:        <span class="hljs-number">42</span>,
            Employed:   <span class="hljs-literal">true</span>,
            Occupation: <span class="hljs-string">"Doctor"</span>,
            Interests:  []<span class="hljs-keyword">string</span>{<span class="hljs-string">"Reading"</span>, <span class="hljs-string">"Swimming"</span>},
        },
        {
            Name:       <span class="hljs-string">"Jessica"</span>,
            Age:        <span class="hljs-number">22</span>,
            Employed:   <span class="hljs-literal">true</span>,
            Occupation: <span class="hljs-string">"Teacher"</span>,
            Interests:  []<span class="hljs-keyword">string</span>{<span class="hljs-string">"Piano"</span>, <span class="hljs-string">"Baking"</span>},
        },
        {
            Name:       <span class="hljs-string">"Ben"</span>,
            Age:        <span class="hljs-number">23</span>,
            Employed:   <span class="hljs-literal">true</span>,
            Occupation: <span class="hljs-string">"Photographer"</span>,
            Interests:  []<span class="hljs-keyword">string</span>{<span class="hljs-string">"Music"</span>, <span class="hljs-string">"Running"</span>},
        },
    }
    tmplFile := <span class="hljs-string">"demo.tmpl"</span>
    tmpl, err := template.New(tmplFile).ParseFiles(tmplFile)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-built_in">panic</span>(err)
    }
    err = tmpl.Execute(os.Stdout, people)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-built_in">panic</span>(err)
    }
}
</code></pre>
<p>Note that I added an attribute called <code>Interests</code> (slice of <code>strings</code>) to the <code>Person</code> struct. For an explanation of this code, please read <a target="_blank" href="https://alissalozhkin.hashnode.dev/how-to-create-plaintext-reports-in-go-using-templates-with-loops-and-conditionals">my previous post</a>.</p>
<p>In <code>demo.tmpl</code>, we can use the <code>slice</code> function and the <code>range</code> action to loop over a section of the slice <code>people</code>.</p>
<pre><code class="lang-go">{{ <span class="hljs-keyword">range</span> slice . <span class="hljs-number">1</span> <span class="hljs-number">2</span> }}
-----------------
Name: {{.Name}}
Age: {{.Age}}
Occupation: {{ <span class="hljs-keyword">if</span> .Employed }}{{ .Occupation }}{{ <span class="hljs-keyword">else</span> }}Unemployed{{end}}
{{ end }}
</code></pre>
<p><code>{{ slice . 1 2 }}</code> is equivalent to <code>people[1:2]</code>, and so calling <code>range</code> on this slice iterates through the second element of <code>people</code> and prints out the following string:</p>
<pre><code class="lang-go">-----------------
Name: Jessica
Age: <span class="hljs-number">22</span>
Occupation: Teacher
</code></pre>
<p>For the purpose of printing out one element, it may be easier to use the <code>index</code> function. For example, the line <code>{{ index . 0 }}</code> is equivalent to <code>people[0]</code> and would print out <code>{Bob 42 true Doctor [Reading Swimming]}</code>.</p>
<p>Creating a plaintext report solely through the use of actions and built-in functions in templates can be quite restrictive as arithmetic operations cannot be used in templates directly.</p>
<p>Introducing the option to feed in custom functions to your templates. These functions can be defined however you want, and they give you the possibility to perform operations that are otherwise not allowed in templates.</p>
<p>Let’s say you want to index the last element of the slice you pass in. If you know the length of the slice, then you can simply hardcode the index number. But to make this more reusable, we need to pass in a custom function that allows us to decrement the length by one so that we can index the last element of any slice.</p>
<p>We start by defining a new function called <code>sub</code> in <code>main.go</code>:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">sub</span><span class="hljs-params">(i <span class="hljs-keyword">int</span>)</span> <span class="hljs-title">int</span></span> {
    <span class="hljs-keyword">return</span> i - <span class="hljs-number">1</span>
}
</code></pre>
<p>In the <code>main</code> function, we create a map <code>fMap</code> that maps a function name (<code>string</code>) to the function definition. We then pass this into the template through the <code>template.New().Funcs</code> function:</p>
<pre><code class="lang-go">fMap := template.FuncMap{
    <span class="hljs-string">"sub"</span>: sub,
}
tmpl, err := template.New(tmplFile).Funcs(fMap).ParseFiles(tmplFile)
<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
    <span class="hljs-built_in">panic</span>(err)
}
err = tmpl.Execute(os.Stdout, people)
<span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
    <span class="hljs-built_in">panic</span>(err)
}
</code></pre>
<p>In the template file, we write <code>{{ len . | sub | index . }}</code> , indicating that the length of the slice is passed to the <code>sub</code> function, and the output of the <code>sub</code> function is passed to the <code>index</code> function. Therefore, when passing in the slice <code>people</code>, the output of this line is <code>people[2]</code> or <code>{ Ben 23 true Photographer [Music Running]}</code>.</p>
<p>In a similar way, we can pass built-in Go functions into a template. For example, let’s say we want to convert the slice of <code>Interests</code> into a string where each interest is separated by <code>&amp;</code> . To do this, we first pass in the function <code>strings.Join</code> to the template by adding a key-value pair to <code>fMap</code> like so:</p>
<pre><code class="lang-go">fMap := template.FuncMap{
    <span class="hljs-string">"sub"</span>:  sub,
    <span class="hljs-string">"join"</span>: strings.Join,
}
</code></pre>
<p>Going back to <code>demo.tmpl</code>, this time looping through the whole slice, we can use this function to return the desired string:</p>
<pre><code class="lang-go">{{ <span class="hljs-keyword">range</span> . }}
-----------------
Name: {{.Name}}
Age: {{.Age}}
Occupation: {{ <span class="hljs-keyword">if</span> .Employed }}{{ .Occupation }}{{ <span class="hljs-keyword">else</span> }}Unemployed{{end}}
Interests: {{ join .Interests <span class="hljs-string">" &amp; "</span> }}
{{ end }}
</code></pre>
<p>Saving <code>demo.tmpl</code> and running <code>go run main.go</code> gives the following result:</p>
<pre><code class="lang-go">-----------------
Name: Bob
Age: <span class="hljs-number">42</span>
Occupation: Doctor
Interests: Reading &amp; Swimming

-----------------
Name: Jessica
Age: <span class="hljs-number">22</span>
Occupation: Teacher
Interests: Piano &amp; Baking

-----------------
Name: Ben
Age: <span class="hljs-number">23</span>
Occupation: Photographer
Interests: Music &amp; Running
</code></pre>
]]></content:encoded></item><item><title><![CDATA[How to Create Plaintext Reports in Go Using Templates with Loops and Conditionals]]></title><description><![CDATA[My previous blog post introduced templates in Go by demoing how to produce a simple string using the template.New().Parse function. In this blog post, I will go over the steps on how to use the text/template package with loops and conditional logic t...]]></description><link>https://blog.gotechwithalissa.com/how-to-create-plaintext-reports-in-go-using-templates-with-loops-and-conditionals</link><guid isPermaLink="true">https://blog.gotechwithalissa.com/how-to-create-plaintext-reports-in-go-using-templates-with-loops-and-conditionals</guid><category><![CDATA[templates in Go]]></category><category><![CDATA[Template actions in Go]]></category><category><![CDATA[golang]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[for loops]]></category><category><![CDATA[Conditional statement]]></category><dc:creator><![CDATA[Alissa Lozhkin]]></dc:creator><pubDate>Tue, 01 Jul 2025 19:39:56 GMT</pubDate><content:encoded><![CDATA[<p>My <a target="_blank" href="https://alissalozhkin.hashnode.dev/introduction-to-go-templates">previous blog post</a> introduced templates in Go by demoing how to produce a simple string using the <code>template.New().Parse</code> function. In this blog post, I will go over the steps on how to use the <code>text/template</code> package with loops and conditional logic to produce a plaintext report. This demo will be using the <code>template.New().ParseFiles</code> function.</p>
<p>First off, we introduce a feature of templates called <code>actions</code>. An <code>action</code>, defined as <code>{{ &lt;action&gt; }}</code>, may be a for-loop, conditional statement, or even a custom function defined by the user. Using the same starter code as in the last post, we have:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"os"</span>
    <span class="hljs-string">"text/template"</span>
)

<span class="hljs-keyword">type</span> Person <span class="hljs-keyword">struct</span> {
    Name       <span class="hljs-keyword">string</span>
    Age        <span class="hljs-keyword">int</span>
    Employed   <span class="hljs-keyword">bool</span>
    Occupation <span class="hljs-keyword">string</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-comment">// insert code here</span>
}
</code></pre>
<p>Note that whenever we want to export a variable or a function in Go, the variable name must begin with a capital letter. Hence, the <code>Person</code> struct and all of its attributes begin with capital letters.</p>
<p>The next step is to create a template file which we will call <code>demo.tmpl</code>. For now, this file will contain some basic text:</p>
<pre><code class="lang-go">Nothing here yet
</code></pre>
<p>In <code>main.go</code>, we create a slice containing a couple of <code>Person</code> objects, which we will then pass to the template file by calling <code>template.Execute</code>.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    people := []Person{
        {
            Name:       <span class="hljs-string">"Bob"</span>,
            Age:        <span class="hljs-number">42</span>,
            Employed:   <span class="hljs-literal">true</span>,
            Occupation: <span class="hljs-string">"Doctor"</span>,
        },
        {
            Name:       <span class="hljs-string">"Jessica"</span>,
            Age:        <span class="hljs-number">22</span>,
            Employed:   <span class="hljs-literal">false</span>,
            Occupation: <span class="hljs-string">""</span>,
        },
    }
}
</code></pre>
<p>In the same file, we then call <code>template.New().ParseFiles</code>. This function initializes a template with the filename <code>demo.tmpl</code> and parses it to ensure that there are no syntax errors. The <code>panic</code> function ensures quick error-handling. We then execute the template using <code>template.Execute</code>, with the slice <code>people</code> as the second argument, as can be seen below:</p>
<pre><code class="lang-go">    tmplFile := <span class="hljs-string">"demo.tmpl"</span>
    tmpl, err := template.New(tmplFile).ParseFiles(tmplFile)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-built_in">panic</span>(err)
    }
    err = tmpl.Execute(os.Stdout, people)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-built_in">panic</span>(err)
    }
</code></pre>
<p>If we run <code>go run main.go</code>, on the terminal will be printed the string <code>nothing here yet</code>, as this is the only string written in the file at the moment.</p>
<p>We therefore begin populating the template file. We can use the <code>range</code> action to iterate through the slice that was passed in.</p>
<pre><code class="lang-go">{{ <span class="hljs-keyword">range</span> . }}
-----------------
Name: {{.Name}}
Age: {{.Age}}
{{ end }}
</code></pre>
<p>In the command <code>{{ range . }}</code>, the <code>.</code> represents the slice. The <code>range</code> action is also terminated with <code>{{ end }}</code>. In the code block above, we access the name and age of each <code>Person</code> object in the <code>people</code> slice. Running <code>go run main.go</code> gives us the following result:</p>
<pre><code class="lang-go">-----------------
Name: Bob
Age: <span class="hljs-number">42</span>

-----------------
Name: Jessica
Age: <span class="hljs-number">22</span>
</code></pre>
<p>We want to display the occupation of each <code>Person</code> conditionally: if <code>Employed</code> is true, then display the occupation, otherwise display <code>Unemployed</code>. Both the <code>if</code> and <code>else</code> actions are used for this as seen below:</p>
<pre><code class="lang-go">{{ <span class="hljs-keyword">range</span> . }}
-----------------
Name: {{.Name}}
Age: {{.Age}}
Occupation: {{ <span class="hljs-keyword">if</span> .Employed }}{{ .Occupation }}{{ <span class="hljs-keyword">else</span> }}Unemployed{{end}}
{{ end }}
</code></pre>
<p>Note that the conditional statement is also terminated with <code>{{ end }}</code>. Running <code>go run main.go</code> gives us the following result:</p>
<pre><code class="lang-go">-----------------
Name: Bob
Age: <span class="hljs-number">42</span>
Occupation: Doctor

-----------------
Name: Jessica
Age: <span class="hljs-number">22</span>
Occupation: Unemployed
</code></pre>
<p>At the top of the file, we want to include the number of people contained in the slice. We can do so by using the <code>len</code> action like so:</p>
<pre><code class="lang-go">People: {{ <span class="hljs-built_in">len</span> . -}}
{{ <span class="hljs-keyword">range</span> . }}
-----------------
Name: {{.Name}}
Age: {{.Age}}
Occupation: {{ <span class="hljs-keyword">if</span> .Employed }}{{ .Occupation }}{{ <span class="hljs-keyword">else</span> }}Unemployed{{end}}
{{ end }}
</code></pre>
<p>Note that in the command <code>{{ len . -}}</code>, the <code>.</code> represents the slice and the <code>-</code> indicates that a newline character <code>\n</code> should not be printed after the first line. Running <code>go run main.go</code> gives us the final result:</p>
<pre><code class="lang-go">People: <span class="hljs-number">2</span>
-----------------
Name: Bob
Age: <span class="hljs-number">42</span>
Occupation: Doctor

-----------------
Name: Jessica
Age: <span class="hljs-number">22</span>
Occupation: Unemployed
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Introduction to Go Templates]]></title><description><![CDATA[Using templates in Go is a great way to produce content in a dynamic way. Go makes it possible to prepare content for display as pure text (by using the text/template package or as HTML with proper encoding (by using the html/template package). Both ...]]></description><link>https://blog.gotechwithalissa.com/introduction-to-go-templates</link><guid isPermaLink="true">https://blog.gotechwithalissa.com/introduction-to-go-templates</guid><category><![CDATA[structs in Go]]></category><category><![CDATA[Go Language]]></category><category><![CDATA[golang]]></category><category><![CDATA[Golang Templates]]></category><dc:creator><![CDATA[Alissa Lozhkin]]></dc:creator><pubDate>Fri, 13 Jun 2025 22:36:36 GMT</pubDate><content:encoded><![CDATA[<p>Using templates in Go is a great way to produce content in a dynamic way. Go makes it possible to prepare content for display as pure text (by using the <code>text/template</code> package or as HTML with proper encoding (by using the <code>html/template</code> package). Both of these packages can be found in the Go standard library, and they are incredibly useful in presenting data neatly. In this blog post, I will introduce templates in Go by going over the steps to produce one line of formatted content from a template string.</p>
<p>The first step is to create a Go file called <code>main.go</code> that imports the necessary packages and defines the <code>main</code> function.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"os"</span>
    <span class="hljs-string">"text/template"</span>
)

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-comment">// insert code here</span>
}
</code></pre>
<p>For this tutorial, I will be using a struct called <code>Person</code>, which can be defined as so:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Person <span class="hljs-keyword">struct</span> {
    Name       <span class="hljs-keyword">string</span>
    Age        <span class="hljs-keyword">int</span>
}
</code></pre>
<p>In <code>main.go</code>, we first initialize a new template called <code>demo</code>, and we then parse the template string to ensure there are no syntax errors. We use the <code>panic</code> function to handle errors quickly. We then execute the template using the <code>Execute</code> function which takes in two arguments: the first argument is to specify where you want the final report to be printed (this could be another file or the terminal). For this demo, the final report will be printed to the terminal (<code>os.Stdout</code>). The second argument specifies the data that is sent to the template string. In this demo, one instance of the struct <code>Person</code> is passed into the template string. Code for this step is shown below:</p>
<pre><code class="lang-go">    person := Person{<span class="hljs-string">"Alex"</span>, <span class="hljs-number">32</span>}
    tmpl, err := template.New(<span class="hljs-string">"demo"</span>).Parse(<span class="hljs-string">"{{.Name}} is {{.Age}} years old"</span>)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-built_in">panic</span>(err)
    }
    err = tmpl.Execute(os.Stdout, person)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-built_in">panic</span>(err)
    }
</code></pre>
<p>In the template string, both the <code>Name</code> and <code>Age</code> attributes of the <code>Person</code> object are accessed by prepending a <code>.</code> to the attribute name. The <code>.</code> here represents the <code>Person</code> object. <code>Main.go</code> now looks like this:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"os"</span>
    <span class="hljs-string">"text/template"</span>
)

<span class="hljs-keyword">type</span> Person <span class="hljs-keyword">struct</span> {
    Name       <span class="hljs-keyword">string</span>
    Age        <span class="hljs-keyword">int</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    person := Person{<span class="hljs-string">"Alex"</span>, <span class="hljs-number">32</span>}
    tmpl, err := template.New(<span class="hljs-string">"demo"</span>).Parse(<span class="hljs-string">"{{.Name}} is {{.Age}} years old"</span>)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-built_in">panic</span>(err)
    }
    err = tmpl.Execute(os.Stdout, person)
    <span class="hljs-keyword">if</span> err != <span class="hljs-literal">nil</span> {
        <span class="hljs-built_in">panic</span>(err)
    }
}
</code></pre>
<p>After running <code>go run main.go</code>, you will get the following output in the terminal:</p>
<pre><code class="lang-go">Alex is <span class="hljs-number">32</span> years old
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Introduction to Go's Make Function]]></title><description><![CDATA[In my two previous blog posts, I wrote about how to create stacks and queues using the struct data type, which is specifically helpful when one wants to define a maximum capacity for the queue/stack. We can also define a maximum capacity for a slice ...]]></description><link>https://blog.gotechwithalissa.com/introduction-to-gos-make-function</link><guid isPermaLink="true">https://blog.gotechwithalissa.com/introduction-to-gos-make-function</guid><category><![CDATA[make function]]></category><category><![CDATA[golang]]></category><category><![CDATA[golang slices]]></category><dc:creator><![CDATA[Alissa Lozhkin]]></dc:creator><pubDate>Fri, 06 Jun 2025 19:18:53 GMT</pubDate><content:encoded><![CDATA[<p>In my two previous blog posts, I wrote about how to create stacks and queues using the <code>struct</code> data type, which is specifically helpful when one wants to define a maximum capacity for the queue/stack. We can also define a maximum capacity for a slice using the <code>make</code> function, which takes in three arguments: <code>type</code>, <code>length</code>, and <code>capacity</code> (optional, defaults to <code>length</code> if not specified). For <code>type</code>, a slice or a map can be specified. We can initialize a slice in the following way:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

s := <span class="hljs-built_in">make</span>([]<span class="hljs-keyword">int</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
<span class="hljs-keyword">for</span> i := <span class="hljs-keyword">range</span> s {
    s[i] = i+<span class="hljs-number">1</span>
}

fmt.Println(s, <span class="hljs-built_in">len</span>(s), <span class="hljs-built_in">cap</span>(s)) <span class="hljs-comment">// [1 2] 2 3</span>
</code></pre>
<p>Note that if we were to add an element such that we exceed the slice’s capacity, the capacity will automatically increase. Therefore, in order to add/remove elements from the slice without exceeding its capacity, we first check whether its length, <code>len(s)</code>, is equal to the capacity, <code>cap(s)</code>.</p>
]]></content:encoded></item><item><title><![CDATA[How to Create a Stack in Go]]></title><description><![CDATA[Like a queue, the stack data structure can store objects, allowing the user to add and remove objects from it. In contrast to a queue, a stack uses the “Last In, First out” (LIFO) principle to do this. Similarly to a queue, the best way to implement ...]]></description><link>https://blog.gotechwithalissa.com/how-to-create-a-stack-in-go</link><guid isPermaLink="true">https://blog.gotechwithalissa.com/how-to-create-a-stack-in-go</guid><category><![CDATA[golang]]></category><category><![CDATA[stack]]></category><category><![CDATA[data structures]]></category><category><![CDATA[struct and methods in go]]></category><dc:creator><![CDATA[Alissa Lozhkin]]></dc:creator><pubDate>Fri, 30 May 2025 20:13:39 GMT</pubDate><content:encoded><![CDATA[<p>Like a queue, the stack data structure can store objects, allowing the user to add and remove objects from it. In contrast to a queue, a stack uses the “Last In, First out” (LIFO) principle to do this. Similarly to a queue, the best way to implement a stack is by creating a <code>struct</code>. Many of the methods for the stack struct were already implemented for the queue struct in this <a target="_blank" href="https://alissalozhkin.hashnode.dev/how-to-create-a-queue-in-go">blog post</a>. Therefore, we have the following starter code:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Stack <span class="hljs-keyword">struct</span> {
    elements []<span class="hljs-keyword">int</span>  <span class="hljs-comment">// stores the objects in the stack</span>
    size     <span class="hljs-keyword">int</span>  <span class="hljs-comment">// the maximum size of the stack</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *Stack)</span> <span class="hljs-title">GetLength</span><span class="hljs-params">()</span> <span class="hljs-title">int</span></span> {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">len</span>(s.elements) <span class="hljs-comment">// return current length of the stack</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *Stack)</span> <span class="hljs-title">Add</span><span class="hljs-params">(element <span class="hljs-keyword">int</span>)</span></span> {
    <span class="hljs-keyword">if</span> s.GetLength() == s.size { <span class="hljs-comment">// if the stack is at max length, don't add new element</span>
        fmt.Println(<span class="hljs-string">"Stack is full"</span>)
        <span class="hljs-keyword">return</span>
    } <span class="hljs-keyword">else</span> {
        s.elements = <span class="hljs-built_in">append</span>(s.elements, element)
        <span class="hljs-keyword">return</span>
    }
}
</code></pre>
<p>We then define a new method called <code>Pop</code> with the following implementation:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *Stack)</span> <span class="hljs-title">Pop</span><span class="hljs-params">()</span> <span class="hljs-title">int</span></span> {
    <span class="hljs-keyword">if</span> s.GetLength() == <span class="hljs-number">0</span> { <span class="hljs-comment">// if stack is empty, there is nothing to pop</span>
        fmt.Println(<span class="hljs-string">"Stack is empty"</span>)
        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> s.GetLength() == <span class="hljs-number">1</span> {
        temp := s.elements[<span class="hljs-number">0</span>]
        s.elements = s.elements[:<span class="hljs-number">0</span>] <span class="hljs-comment">// if current length is 1, stack becomes empty</span>
        <span class="hljs-keyword">return</span> temp
    } <span class="hljs-keyword">else</span> {
        length := s.GetLength()
        temp := s.elements[length<span class="hljs-number">-1</span>]
        s.elements = s.elements[:length<span class="hljs-number">-1</span>]
        <span class="hljs-keyword">return</span> temp <span class="hljs-comment">// return the popped element</span>
    }
}
</code></pre>
<p>We can then define the <code>main</code> function to create and modify a <code>stack</code> object:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    s := Stack{size: <span class="hljs-number">3</span>} <span class="hljs-comment">// creates a stack with a max size of 3</span>
    s.Add(<span class="hljs-number">1</span>)
    s.Add(<span class="hljs-number">2</span>)
    s.Add(<span class="hljs-number">3</span>)
    s.Add(<span class="hljs-number">4</span>)  <span class="hljs-comment">// Stack is full</span>
    fmt.Println(s.elements) <span class="hljs-comment">// [1, 2, 3]</span>
    elem1 := s.Pop()
    elem2 := s.Pop()
    elem3 := s.Pop()
    fmt.Println(elem1, elem2, elem3) <span class="hljs-comment">// 3, 2, 1</span>
    s.Pop() <span class="hljs-comment">// Stack is empty</span>
    fmt.Println(s.elements) <span class="hljs-comment">// []</span>
}
</code></pre>
<p>The <code>stack</code> data structure is now implemented!</p>
]]></content:encoded></item><item><title><![CDATA[How to Create a Queue in Go]]></title><description><![CDATA[A queue is a very useful data structure where one can store, add, and remove objects with the “First in, First out” (FIFO) principle. Queues are very useful for basic algorithms (such as bread-first search), so it is therefore worth learning how to i...]]></description><link>https://blog.gotechwithalissa.com/how-to-create-a-queue-in-go</link><guid isPermaLink="true">https://blog.gotechwithalissa.com/how-to-create-a-queue-in-go</guid><category><![CDATA[Go Language]]></category><category><![CDATA[Queues]]></category><category><![CDATA[structs Go]]></category><dc:creator><![CDATA[Alissa Lozhkin]]></dc:creator><pubDate>Fri, 27 Dec 2024 23:03:31 GMT</pubDate><content:encoded><![CDATA[<p>A queue is a very useful data structure where one can store, add, and remove objects with the “First in, First out” (FIFO) principle. Queues are very useful for basic algorithms (such as bread-first search), so it is therefore worth learning how to implement them in Go. The best way to implement a queue using Go is by creating a <code>struct</code>. You can read more about <code>structs</code> in Go in <a target="_blank" href="https://alissalozhkin.hashnode.dev/structs-in-go">this blog post</a>.</p>
<p>The first step is to create the <code>struct</code> and call it <code>Queue</code>.</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> Queue <span class="hljs-keyword">struct</span> {
    elements []<span class="hljs-keyword">int</span>  <span class="hljs-comment">// stores the objects in the queue</span>
    size     <span class="hljs-keyword">int</span>  <span class="hljs-comment">// the maximum size of the queue</span>
}
</code></pre>
<p>After defining the struct, we can define its methods, namely <code>GetLength()</code>, <code>Enqueue()</code>, and <code>Dequeue()</code>. By writing <code>(q *Queue)</code> when defining the function (where <code>q</code> denotes a <code>Queue</code> object), we specify that the method belongs to the <code>struct</code>.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(q *Queue)</span> <span class="hljs-title">GetLength</span><span class="hljs-params">()</span> <span class="hljs-title">int</span></span> {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">len</span>(q.elements) <span class="hljs-comment">// return current length of the queue</span>
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(q *Queue)</span> <span class="hljs-title">Enqueue</span><span class="hljs-params">(element <span class="hljs-keyword">int</span>)</span></span> {
    <span class="hljs-keyword">if</span> q.GetLength() == q.size { <span class="hljs-comment">// if the queue is at max length, don't add new element</span>
        fmt.Println(<span class="hljs-string">"Queue is full"</span>)
        <span class="hljs-keyword">return</span>
    } <span class="hljs-keyword">else</span> {
        q.elements = <span class="hljs-built_in">append</span>(q.elements, element)
        <span class="hljs-keyword">return</span>
    }
}

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(q *Queue)</span> <span class="hljs-title">Dequeue</span><span class="hljs-params">()</span> <span class="hljs-title">int</span></span> {
    <span class="hljs-keyword">if</span> q.GetLength() == <span class="hljs-number">0</span> { <span class="hljs-comment">// if queue is empty, there is nothing to dequeue</span>
        fmt.Println(<span class="hljs-string">"Queue is empty"</span>)
        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> q.GetLength() == <span class="hljs-number">1</span> {
        temp := q.elements[<span class="hljs-number">0</span>]
        q.elements = q.elements[:<span class="hljs-number">0</span>] <span class="hljs-comment">// if current length is 1, queue becomes empty</span>
        <span class="hljs-keyword">return</span> temp
    } <span class="hljs-keyword">else</span> {
        temp := q.elements[<span class="hljs-number">0</span>]
        q.elements = q.elements[<span class="hljs-number">1</span>:]
        <span class="hljs-keyword">return</span> temp <span class="hljs-comment">// return the dequeued element</span>
    }
}
</code></pre>
<p>The last step is to define the main function that will create and modify a <code>queue</code> object:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    q := Queue{size: <span class="hljs-number">3</span>} <span class="hljs-comment">// creates a queue with a max size of 3</span>
    q.Enqueue(<span class="hljs-number">1</span>)
    q.Enqueue(<span class="hljs-number">2</span>)
    q.Enqueue(<span class="hljs-number">3</span>)
    q.Enqueue(<span class="hljs-number">4</span>)  <span class="hljs-comment">// Queue is full</span>
    fmt.Print(q.elements) <span class="hljs-comment">// [1, 2, 3]</span>
    elem1 := q.Dequeue()
    elem2 := q.Dequeue()
    elem3 := q.Dequeue()
    fmt.Println(elem1, elem2, elem3) <span class="hljs-comment">// 1, 2, 3</span>
    q.Dequeue() <span class="hljs-comment">// Queue is empty</span>
}
</code></pre>
<p>The <code>queue</code> data structure is now implemented!</p>
<p>Note that the <code>stack</code> data structure is very similar in implementation. Only the <code>Dequeue()</code> method needs to be changed to remove the last element in <code>elements</code> instead of the first.</p>
]]></content:encoded></item><item><title><![CDATA[Structs in Go]]></title><description><![CDATA[A struct is a composite datatype that groups together many fields of different types into one object. This blog post will go over the basics of how to declare a struct and assign values to its attributes.
In Go, a struct is defined using the type key...]]></description><link>https://blog.gotechwithalissa.com/structs-in-go</link><guid isPermaLink="true">https://blog.gotechwithalissa.com/structs-in-go</guid><category><![CDATA[Go Language]]></category><category><![CDATA[structs Go]]></category><dc:creator><![CDATA[Alissa Lozhkin]]></dc:creator><pubDate>Fri, 25 Oct 2024 20:20:53 GMT</pubDate><content:encoded><![CDATA[<p>A struct is a composite datatype that groups together many fields of different types into one object. This blog post will go over the basics of how to declare a struct and assign values to its attributes.</p>
<p>In Go, a struct is defined using the <code>type</code> keyword. The general way of defining a struct is as follows:</p>
<pre><code class="lang-go"><span class="hljs-keyword">type</span> &lt;struct_name&gt; <span class="hljs-keyword">struct</span> {
    <span class="hljs-comment">// struct attributes</span>
}
</code></pre>
<p>The code block below does two things: it defines a struct called <code>person</code> that has <code>name</code> (type <code>string</code>) and <code>age</code> (type <code>int</code>) as its attributes, and it declares an object of this type:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-keyword">type</span> person <span class="hljs-keyword">struct</span> {
    firstName <span class="hljs-keyword">string</span>
    age <span class="hljs-keyword">int</span>
}
person1 := person{firstName: <span class="hljs-string">"Anna"</span>, age: <span class="hljs-number">35</span>}

fmt.Println(person1)  <span class="hljs-comment">// {Anna 35}</span>
fmt.Println(person1.firstName)  <span class="hljs-comment">// Anna</span>
fmt.Println(person1.age)  <span class="hljs-comment">// 35</span>
</code></pre>
<p>Structs are also mutable, so we can change the value of a struct’s attribute:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

person2 := person{firstName: <span class="hljs-string">"Allison"</span>, age: <span class="hljs-number">20</span>}

fmt.Println(person2)  <span class="hljs-comment">// {Allison 20}</span>
person2.age += <span class="hljs-number">1</span>
fmt.Println(person2)  <span class="hljs-comment">// {Allison 21}</span>
</code></pre>
<p>It is possible that only one variable is a struct, and so it doesn’t make sense to give the struct a name. The following code block creates an object <code>flower</code> with attributes <code>colour</code> and <code>petal_number</code>:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

flower := <span class="hljs-keyword">struct</span> {
    colour       <span class="hljs-keyword">string</span>
    petal_number <span class="hljs-keyword">int</span>
}{
    <span class="hljs-string">"blue"</span>,
    <span class="hljs-number">6</span>,
}
fmt.Println(flower)  <span class="hljs-comment">// {blue 6}</span>
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Strings in Go]]></title><description><![CDATA[Strings are sequences of characters used to represent text, and they can contain letters, digits, and special characters. In Go, strings are immutable. This post will go over the steps on how to declare a string, and it will also go over basic string...]]></description><link>https://blog.gotechwithalissa.com/strings-in-go</link><guid isPermaLink="true">https://blog.gotechwithalissa.com/strings-in-go</guid><category><![CDATA[Go Language]]></category><category><![CDATA[Strings]]></category><category><![CDATA[string functions]]></category><dc:creator><![CDATA[Alissa Lozhkin]]></dc:creator><pubDate>Tue, 22 Oct 2024 14:53:43 GMT</pubDate><content:encoded><![CDATA[<p>Strings are sequences of characters used to represent text, and they can contain letters, digits, and special characters. In Go, strings are immutable. This post will go over the steps on how to declare a string, and it will also go over basic string functions.</p>
<p>Just like any other datatype, a string can be defined using either the <code>var</code> keyword or the shorthand method. Both ways can be seen in the code block below:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> string1 <span class="hljs-keyword">string</span> = <span class="hljs-string">"hello"</span>  <span class="hljs-comment">// using 'var' keyword</span>
string2 := <span class="hljs-string">"hi"</span>  <span class="hljs-comment">// using shorthand method</span>
</code></pre>
<p>In order to use basic string functions in a code block, we have to import the <code>strings</code> package:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"strings"</span>
</code></pre>
<p>We can access many different functions from this package. The following section will present example usage of some of these functions.</p>
<p>The <code>Contains()</code> function returns whether a substring is found in another string. The first parameter is the string we want to search, and the second parameter is the substring we want to search for.</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> (
<span class="hljs-string">"strings"</span>
<span class="hljs-string">"fmt"</span>
)

string3 := <span class="hljs-string">"Hello, how are you?"</span>
contains_o := strings.Contains(string3, <span class="hljs-string">"o"</span>)
contains_q := strings.Contains(string3, <span class="hljs-string">"q"</span>)

fmt.Println(contains_o)  <span class="hljs-comment">// true</span>
fmt.Println(contains_q)  <span class="hljs-comment">// false</span>
</code></pre>
<p>The <code>Index()</code> function returns the index of a specific character in a string. The first parameter is the string we want to search, and the second parameter is the character whose index we want.</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> (
<span class="hljs-string">"strings"</span>
<span class="hljs-string">"fmt"</span>
)

string4 := <span class="hljs-string">"Good morning"</span>
index_o := strings.Index(string4, <span class="hljs-string">"o"</span>)
index_od := strings.Index(string4, <span class="hljs-string">"od"</span>)
index_q := strings.Index(string4, <span class="hljs-string">"q"</span>)

fmt.Println(index_o)  <span class="hljs-comment">// 1</span>
fmt.Println(index_od)  <span class="hljs-comment">// 2</span>
fmt.Println(index_q)  <span class="hljs-comment">// -1: because q is not in the string</span>
</code></pre>
<p><code>Index_o</code> stores the index of the first instance of the letter <code>o</code>. <code>Index_od</code> stores the index of where the substring <code>od</code> starts. Since <code>q</code> is not in <code>string4</code>, <code>-1</code> is returned when trying to get its index.</p>
<p>The <code>Replace()</code> function can be used to replace substring <code>a</code> in a string with substring <code>b</code> a specified number of times (<code>n</code>). The first parameter is the original string from which a copy is returned, the second parameter is <code>a</code> , the third parameter is <code>b</code> , and the fourth parameter is <code>n</code>. The code block below demonstrates how this function works:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> (
<span class="hljs-string">"strings"</span>
<span class="hljs-string">"fmt"</span>
)

string4 := <span class="hljs-string">"ababababa"</span>
string4 = strings.Replace(string4, <span class="hljs-string">"b"</span>, <span class="hljs-string">"a"</span>, <span class="hljs-number">2</span>)
string5 := strings.Replace(string4, <span class="hljs-string">"b"</span>, <span class="hljs-string">"a"</span>, <span class="hljs-number">-1</span>)

fmt.Println(string4)  <span class="hljs-comment">// aaaaababa</span>
fmt.Println(string5)  <span class="hljs-comment">// aaaaaaaaa</span>
</code></pre>
<p>The first example shows the first two instances of <code>b</code> replaced by <code>a</code> The second example - <code>string5</code> - uses <code>-1</code> as the last parameter, which indicates that all instances of ‘b’ should be replaced by <code>a</code>.</p>
<p>The <code>Split()</code> function slices a string into all substrings that are separated by a specified character. The function returns a slice with the substrings as its elements. The code block below demonstrates how this function works:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> (
<span class="hljs-string">"strings"</span>
<span class="hljs-string">"fmt"</span>
)

string6 := <span class="hljs-string">"1-2-3-4"</span>
slice1 := []<span class="hljs-keyword">string</span>{}
slice1 = strings.Split(string4, <span class="hljs-string">"-"</span>)

fmt.Println(slice1)  <span class="hljs-comment">// [1 2 3 4]</span>
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Maps in Go]]></title><description><![CDATA[Maps in Go are the exact same as dictionaries in Python in that they store several key-value pairs. In this post, I will go over how to initialize and use maps in Go.
The basic syntax for creating a map is as follows:
map1 := map[key_datatype]value_d...]]></description><link>https://blog.gotechwithalissa.com/maps-in-go</link><guid isPermaLink="true">https://blog.gotechwithalissa.com/maps-in-go</guid><category><![CDATA[Go Language]]></category><category><![CDATA[golang]]></category><category><![CDATA[maps]]></category><dc:creator><![CDATA[Alissa Lozhkin]]></dc:creator><pubDate>Tue, 27 Aug 2024 22:52:36 GMT</pubDate><content:encoded><![CDATA[<p>Maps in Go are the exact same as dictionaries in Python in that they store several key-value pairs. In this post, I will go over how to initialize and use maps in Go.</p>
<p>The basic syntax for creating a map is as follows:</p>
<pre><code class="lang-go">map1 := <span class="hljs-keyword">map</span>[key_datatype]value_datatype{key-value pairs}
</code></pre>
<p>The code block below demonstrates how one can create a map with strings mapping to integers.</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

map2 := <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>{}  <span class="hljs-comment">// an empty map</span>
map3 := <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>{<span class="hljs-string">"a"</span>: <span class="hljs-number">1</span>, <span class="hljs-string">"b"</span>: <span class="hljs-number">2</span>}  <span class="hljs-comment">// a non-empty map</span>

fmt.Println(map2)
fmt.Println(map3)
<span class="hljs-comment">// output: </span>
<span class="hljs-comment">//    map[]</span>
<span class="hljs-comment">//    map[a:1 b:2]</span>
</code></pre>
<p>Once a map is initialized, there are many things that we can do with it. For instance, we can access the value of a certain key in the map by doing the following:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

map4 := <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>{<span class="hljs-string">"x"</span>: <span class="hljs-number">1</span>, <span class="hljs-string">"y"</span>: <span class="hljs-number">2</span>}

fmt.Println(map4[<span class="hljs-string">"x"</span>])
<span class="hljs-comment">// output = 1</span>
</code></pre>
<p>You may think that trying to access the value of a key that does not exist in the map will give you an error (like in Python). However, in Go, the value returned will be 0 (if the value datatype is an integer), 0.0 (if the value datatype is a float), or "" (if the value datatype is a string). This may be confusing because an actually existing key in the map may have the value 0. Therefore, to determine whether a key is in a map, we can do the following:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

map5 := <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>{<span class="hljs-string">"x"</span>: <span class="hljs-number">1</span>, <span class="hljs-string">"y"</span>: <span class="hljs-number">2</span>}
_, exists_x := map5[<span class="hljs-string">"x"</span>]
_, exists_z := map5[<span class="hljs-string">"z"</span>]

fmt.Println(exists_x)
fmt.Println(exists_z)
<span class="hljs-comment">// output =</span>
<span class="hljs-comment">//    true</span>
<span class="hljs-comment">//    false</span>
</code></pre>
<p>The '_' seen in the examples above is known as the <code>blank identifier</code> . Both examples have two parameters returned, the value of the key and whether the key is in the map. Since only the latter is used in the code, we can disregard the former by using '_'.</p>
<p>We can also assign a new value to a key in the map. The code block below demonstrates how we can do this:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

map5 := <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>{<span class="hljs-string">"animals"</span>: <span class="hljs-number">4</span>, <span class="hljs-string">"plants"</span>: <span class="hljs-number">3</span>}
map5[<span class="hljs-string">"animals"</span>] = <span class="hljs-number">10</span>

fmt.Println(map5[<span class="hljs-string">"animals"</span>])
<span class="hljs-comment">// output = 10</span>
</code></pre>
<p>We can also add/delete a key from the map:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-comment">// adding a key</span>
map6 := <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>{<span class="hljs-string">"lions"</span>: <span class="hljs-number">1</span>, <span class="hljs-string">"buffalo"</span>: <span class="hljs-number">2</span>}
map6[<span class="hljs-string">"giraffes"</span>] = <span class="hljs-number">3</span>
fmt.Println(map6)
<span class="hljs-comment">// output: map[buffalo:2 giraffes:3 lions:1]</span>

<span class="hljs-comment">// deleting a key</span>
<span class="hljs-built_in">delete</span>(map6, <span class="hljs-string">"lions"</span>)  <span class="hljs-comment">// "delete" function takes in a map and a key</span>
fmt.Println(map6)
<span class="hljs-comment">// output: map[buffalo:2 giraffes:3]</span>
</code></pre>
<p>Note that the map is outputted with the keys in alphabetical order.</p>
<p>We can also iterate through a map using the for-each range loop (see <a target="_blank" href="https://alissalozhkin.hashnode.dev/forwhile-loops-in-go">this post</a> for more details).</p>
<pre><code class="lang-go">map7 := <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>{<span class="hljs-string">"x"</span>: <span class="hljs-number">5</span>, <span class="hljs-string">"y"</span>: <span class="hljs-number">6</span>}
<span class="hljs-keyword">for</span> k, v := <span class="hljs-keyword">range</span> map7 {
    fmt.Println(k, v)  <span class="hljs-comment">// print both the key and value side-by-side</span>
}
<span class="hljs-comment">// output: </span>
<span class="hljs-comment">//    x 5</span>
<span class="hljs-comment">//    y 6</span>
</code></pre>
]]></content:encoded></item><item><title><![CDATA[For/While Loops in Go]]></title><description><![CDATA[In addition to conditionals, loops are fundamental constructs that can be used to control the flow of a program. In this post, I will go over how to create and use both for loops and while loops.
For loops are used in two cases: either we want to exe...]]></description><link>https://blog.gotechwithalissa.com/forwhile-loops-in-go</link><guid isPermaLink="true">https://blog.gotechwithalissa.com/forwhile-loops-in-go</guid><category><![CDATA[for-each-loop]]></category><category><![CDATA[golang]]></category><category><![CDATA[for loop]]></category><category><![CDATA[while loop]]></category><dc:creator><![CDATA[Alissa Lozhkin]]></dc:creator><pubDate>Mon, 19 Aug 2024 23:44:38 GMT</pubDate><content:encoded><![CDATA[<p>In addition to conditionals, loops are fundamental constructs that can be used to control the flow of a program. In this post, I will go over how to create and use both for loops and while loops.</p>
<p>For loops are used in two cases: either we want to execute a block of code a set number of times, or we want to iterate through elements of some data structure (ex. an array).</p>
<p>The code block below demonstrates how a for loop can be used to execute a block of code a set number of times:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

n := <span class="hljs-number">10</span>
<span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++ {  <span class="hljs-comment">// repeat 10 times</span>
    n++  <span class="hljs-comment">// increment n by 1</span>
}
fmt.Println(n)
<span class="hljs-comment">// output: n = 20</span>
</code></pre>
<p>Looping through elements of an array or slice can either be done with the method above (with 'i' acting as the index) or with another loop called the for-each range loop shown below:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

arr := [<span class="hljs-number">5</span>]{<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}
<span class="hljs-keyword">for</span> i := <span class="hljs-keyword">range</span> arr {
    arr[i] += <span class="hljs-number">2</span>  <span class="hljs-comment">// increment each element in 'arr' by 2</span>
}

fmt.Println(arr)
<span class="hljs-comment">// output: [3, 4, 5, 6, 7]</span>
</code></pre>
<p>In the for-each range loop, we have access to both the index and the value of each element in the array. The example below demonstrates how this can be useful:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

slice1 := []<span class="hljs-keyword">int</span>{<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>}  <span class="hljs-comment">// 'slice1' is a slice, not an array</span>
<span class="hljs-keyword">for</span> i, v := <span class="hljs-keyword">range</span> slice1 {
    fmt.Println(i, v)  <span class="hljs-comment">// print each index-value pair in slice1</span>
}

<span class="hljs-comment">// output: </span>
<span class="hljs-comment">//    0 1</span>
<span class="hljs-comment">//    1 2</span>
<span class="hljs-comment">//    2 3</span>
<span class="hljs-comment">//    3 5</span>
</code></pre>
<p>For while loops, instead of using the 'while' keyword (as in C, Python, and Java), Go uses the 'for' keyword. However, instead of being paired with an incremental variable, the 'for' keyword is paired with a condition. Therefore, the for loop will continue iterating while the condition is not met.</p>
<p>The code block below demonstrates how this type of for loop can be used:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

n := <span class="hljs-number">0</span>
slice2 := []<span class="hljs-keyword">int</span>  <span class="hljs-comment">// an empty slice is initiated</span>
<span class="hljs-keyword">for</span> n &lt; <span class="hljs-number">10</span>:
    slice2 = <span class="hljs-built_in">append</span>(slice2, n)  <span class="hljs-comment">// append 'n' to 'slice2'</span>
    n++  <span class="hljs-comment">// increment 'n' by 1</span>

fmt.Println(slice2)
<span class="hljs-comment">// output: [0 1 2 3 4 5 6 7 8 9]</span>
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Conditionals in Go]]></title><description><![CDATA[Conditional constructs are very useful in programming as they allow complex logic to be implemented within code. In this blog post, I will go over the methods on how to execute a code block conditionally.
The first method is to use an if statement. T...]]></description><link>https://blog.gotechwithalissa.com/conditionals-in-go</link><guid isPermaLink="true">https://blog.gotechwithalissa.com/conditionals-in-go</guid><category><![CDATA[go short variable declaration]]></category><category><![CDATA[golang]]></category><category><![CDATA[Conditionals]]></category><category><![CDATA[IfElseStatement]]></category><dc:creator><![CDATA[Alissa Lozhkin]]></dc:creator><pubDate>Fri, 16 Aug 2024 17:25:58 GMT</pubDate><content:encoded><![CDATA[<p>Conditional constructs are very useful in programming as they allow complex logic to be implemented within code. In this blog post, I will go over the methods on how to execute a code block conditionally.</p>
<p>The first method is to use an if statement. The code block below demonstrates how this can be done:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-keyword">var</span> a <span class="hljs-keyword">int</span> = <span class="hljs-number">1</span>
<span class="hljs-keyword">if</span> a == <span class="hljs-number">1</span> {  <span class="hljs-comment">// the condition checks whether a is equal to 1</span>
      a++
}
fmt.Println(a)  
<span class="hljs-comment">//output: 2</span>
</code></pre>
<p>Note that the condition which is being evaluated does not have to be in brackets.</p>
<p>If/else statements can be used when we want <code>code block 1</code> to be executed when condition <code>a</code> is true and <code>code block 2</code> to be executed when condition <code>a</code> is false.</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-keyword">var</span> a <span class="hljs-keyword">int</span> = <span class="hljs-number">2</span>
<span class="hljs-keyword">if</span> a == <span class="hljs-number">1</span> {
    fmt.Println(<span class="hljs-string">"a is equal to 1"</span>)
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> a &lt; <span class="hljs-number">1</span> {  <span class="hljs-comment">// the condition checks whether a is less than 1</span>
    fmt.Println(<span class="hljs-string">"a is less than 1"</span>)
} <span class="hljs-keyword">else</span> {  <span class="hljs-comment">// proceed if both conditions above are false</span>
    fmt.Println(<span class="hljs-string">"a is greater than 1"</span>)
}
<span class="hljs-comment">// output: a is greater than 1</span>
</code></pre>
<p>Another conditional construct is a switch statement. A switch statement can be used when an expression needs to be compared to multiple different values. The code block below demonstrates how switch statements can be used:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-keyword">var</span> a = <span class="hljs-number">2</span>
<span class="hljs-keyword">switch</span> a {
    <span class="hljs-keyword">case</span> <span class="hljs-number">1</span>: <span class="hljs-comment">// does a == 1?</span>
        fmt.Println(<span class="hljs-string">"a is equal to 1"</span>)
    <span class="hljs-keyword">case</span> <span class="hljs-number">2</span>: <span class="hljs-comment">// does a == 2?</span>
        fmt.Println(<span class="hljs-string">"a is equal to 2"</span>)
}
<span class="hljs-comment">// output: a is equal to 2</span>
</code></pre>
<p>A switch statement can have a default case as well. An example below shows this:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-keyword">var</span> a = <span class="hljs-number">3</span>
<span class="hljs-keyword">switch</span> a {
    <span class="hljs-keyword">case</span> <span class="hljs-number">1</span>:  <span class="hljs-comment">// does a == 1?</span>
        fmt.Println(<span class="hljs-string">"a is equal to 1"</span>)
    <span class="hljs-keyword">case</span> <span class="hljs-number">2</span>: <span class="hljs-comment">// does a == 2?</span>
        fmt.Println(<span class="hljs-string">"a is equal to 2"</span>)
    <span class="hljs-keyword">default</span>:
        fmt.Println(<span class="hljs-string">"a is neither 1 nor 2"</span>)

<span class="hljs-comment">// output: a is neither 1 nor 2</span>
</code></pre>
<p>In both if/else and switch statements, it is possible to declare a variable inside the statement. Note that this variable would only exist within the scope of the conditional construct.</p>
<p>The code block below demonstrates how a variable can be declared in an if/else statement.</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-keyword">if</span> b := <span class="hljs-number">10</span>; b % <span class="hljs-number">2</span> == <span class="hljs-number">0</span> {  <span class="hljs-comment">// define b = 10, check if b is divisible by 2</span>
    b++  <span class="hljs-comment">// increment 'b' by 1</span>
    fmt.Println(b)
} <span class="hljs-keyword">else</span> {
    b += <span class="hljs-number">2</span>  <span class="hljs-comment">// increment 'b' by 2</span>
    fmt.Println(b)
}
<span class="hljs-comment">// output: 11</span>
</code></pre>
<p>Note that it is not possible to print <code>b</code> outside of the if/else statement because it is only defined within the scope of the statement.</p>
<p>The code block below demonstrates how a variable can be declared inside a switch statement:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-keyword">switch</span> b := <span class="hljs-number">3</span>; b {
    <span class="hljs-keyword">case</span> <span class="hljs-number">1</span>:  <span class="hljs-comment">// does b == 1?</span>
        fmt.Println(<span class="hljs-string">"b is equal to 1"</span>)
    <span class="hljs-keyword">case</span> <span class="hljs-number">2</span>: <span class="hljs-comment">// does b == 2?</span>
        fmt.Println(<span class="hljs-string">"b is equal to 2"</span>)
    <span class="hljs-keyword">default</span>:
        fmt.Println(<span class="hljs-string">"b is neither 1 nor 2"</span>)
<span class="hljs-comment">// output: b is neither 1 nor 2</span>
</code></pre>
<p>By tightly scoping a variable to where it is needed and by making the code more concise, declaring a variable within a conditional construct can improve code readability and maintainability.</p>
]]></content:encoded></item><item><title><![CDATA[Slices in Go]]></title><description><![CDATA[Another datatype similar to arrays but less restrictive is a slice. Slices are less restrictive than arrays because they can dynamically grow and shrink in size. Therefore, we can easily append to or remove an element from them. This post will go ove...]]></description><link>https://blog.gotechwithalissa.com/slices-in-go</link><guid isPermaLink="true">https://blog.gotechwithalissa.com/slices-in-go</guid><category><![CDATA[underlying arrays]]></category><category><![CDATA[golang]]></category><category><![CDATA[slices]]></category><dc:creator><![CDATA[Alissa Lozhkin]]></dc:creator><pubDate>Tue, 06 Aug 2024 18:27:28 GMT</pubDate><content:encoded><![CDATA[<p>Another datatype similar to arrays but less restrictive is a slice. Slices are less restrictive than arrays because they can dynamically grow and shrink in size. Therefore, we can easily append to or remove an element from them. This post will go over the steps on how to initialize a slice and also how to append to and remove from a slice.</p>
<p>There are a few ways to initialize a slice. The first way is very similar to how we initialize an array:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> slice1 = []<span class="hljs-keyword">int</span>{} <span class="hljs-comment">// initializes an empty slice with undefined length</span>
<span class="hljs-keyword">var</span> slice2 = []<span class="hljs-keyword">int</span>{<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>}  <span class="hljs-comment">// initalizes a non-empty slice</span>
</code></pre>
<p>Note that in the square brackets on the right side of the equal sign, no length is specified (unlike for an array).</p>
<p>The second way is to create a slice from an array:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> arr1 = [<span class="hljs-number">5</span>]<span class="hljs-keyword">int</span>{<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}
slice3 := arr1[<span class="hljs-number">1</span>:<span class="hljs-number">4</span>]  <span class="hljs-comment">// slice3 = [2, 3, 4]</span>
</code></pre>
<p>When a slice is created from an array, it is a pointer to a specific section of the array. Because of this, when modifying a slice, the same modifications will show up in the underlying array. This can be illustrated in the code block below:</p>
<pre><code class="lang-go">slice3[<span class="hljs-number">0</span>] = <span class="hljs-number">44</span>  <span class="hljs-comment">// slice3 = [44, 3, 4]</span>
fmt.Println(arr1)  <span class="hljs-comment">// [1, 44, 3, 4, 5]</span>
</code></pre>
<p>Elements can be added to a slice simply by using the "append" function. The first argument of this function is a slice and the rest are values that should be appended to the final slice. In the code below, we update the value of slice4 to be the original slice4 (containing values 5, 6, and 7) plus the values 8, 9, and 10:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> slice4 = []<span class="hljs-keyword">int</span>{<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>}  <span class="hljs-comment">// slice4 = [5, 6, 7]</span>
slice4 = <span class="hljs-built_in">append</span>(slice4, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>)  <span class="hljs-comment">// slice4 = [5, 6, 7, 8, 9, 10]</span>
</code></pre>
<p>Removing an element from a slice is done by using the "append" function as well. The code block below gives an example of how this is done:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> slice5 = []<span class="hljs-keyword">int</span>{<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}  <span class="hljs-comment">// slice5 = [1, 2, 3, 4, 5]</span>
slice5 = <span class="hljs-built_in">append</span>(slice5[:<span class="hljs-number">2</span>], slice5[<span class="hljs-number">3</span>:]...)  <span class="hljs-comment">// slice5 = [1, 2, 4, 5]</span>
</code></pre>
<p>We can see that the value at the second index of "slice5" is removed by updating the value of "slice5" to be slice5[:2] plus slice5[3:] ([1, 2] + [4, 5]).</p>
]]></content:encoded></item><item><title><![CDATA[How to Initialize an Array in Go]]></title><description><![CDATA[An array is one of the fundamental data structures for programming. By being able to store multiple different values of the same type, arrays are important for maintaining organization and efficiency of data. This post will go through the different w...]]></description><link>https://blog.gotechwithalissa.com/how-to-initialize-an-array-in-go</link><guid isPermaLink="true">https://blog.gotechwithalissa.com/how-to-initialize-an-array-in-go</guid><category><![CDATA[array]]></category><category><![CDATA[multi-dimensional arrays]]></category><category><![CDATA[Go Language]]></category><dc:creator><![CDATA[Alissa Lozhkin]]></dc:creator><pubDate>Tue, 23 Jul 2024 15:55:27 GMT</pubDate><content:encoded><![CDATA[<p>An array is one of the fundamental data structures for programming. By being able to store multiple different values of the same type, arrays are important for maintaining organization and efficiency of data. This post will go through the different ways one can initialize an array in Go.</p>
<p>Let's say that we want to initialize an array without assigning it a value. The code block below creates an empty integer array with a maximum length of 5:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> arr[<span class="hljs-number">5</span>]<span class="hljs-keyword">int</span>
</code></pre>
<p>When an integer array is initialized as empty, each position in the array has the value 0. Similarly, when a float array is initialized as empty, each position has the value 0.0.</p>
<p>We can also initialize an array and assign it a value at the same time. The code block below initializes an array that stores values 1, 3, and 4:</p>
<pre><code class="lang-go">arr1 := [<span class="hljs-number">3</span>]<span class="hljs-keyword">int</span>{<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>}  <span class="hljs-comment">// array "arr1" has length of 3</span>
</code></pre>
<p>Lastly, we can also initialize and assign a value to a multi-dimensional array in the same way. The code block below initializes two 2x2 arrays: an empty one named "arr" and a non-empty one named "arr1":</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> arr[<span class="hljs-number">2</span>][<span class="hljs-number">2</span>]<span class="hljs-keyword">int</span>
arr1 := [<span class="hljs-number">2</span>][<span class="hljs-number">2</span>]<span class="hljs-keyword">int</span>{
    {<span class="hljs-number">1</span>, <span class="hljs-number">1</span>}, 
    {<span class="hljs-number">2</span>, <span class="hljs-number">2</span>},
}
</code></pre>
]]></content:encoded></item><item><title><![CDATA[How to Read User Input Using Go]]></title><description><![CDATA[Just like printing to the console, reading input from the console with Go is very straightforward. This post aims to teach you just that by going through the steps on how to create a script that outputs 'Hello {name}', where {name} is provided by use...]]></description><link>https://blog.gotechwithalissa.com/how-to-read-user-input-using-go</link><guid isPermaLink="true">https://blog.gotechwithalissa.com/how-to-read-user-input-using-go</guid><category><![CDATA[I/O functions]]></category><category><![CDATA[Go Language]]></category><dc:creator><![CDATA[Alissa Lozhkin]]></dc:creator><pubDate>Wed, 03 Jul 2024 16:08:05 GMT</pubDate><content:encoded><![CDATA[<p>Just like printing to the console, reading input from the console with Go is very straightforward. This post aims to teach you just that by going through the steps on how to create a script that outputs 'Hello {name}', where {name} is provided by user input.</p>
<p>To read user input, Go uses a function called 'Scan()', which can be found in the 'fmt' package, so we need to import it. Assuming the code will reside in the function 'main', we get the following starter code:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-comment">// write code here</span>
}
</code></pre>
<p>In the main function, we first want to declare a string variable that will store the user's input. We can call this variable 'firstName'.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">var</span> firstName <span class="hljs-keyword">string</span>
}
</code></pre>
<p>We can then use the 'Scan()' function to get the user input and store it into the 'firstName' variable. It is important to understand that 'Scan()' takes in a pointer to a variable. This is because Go needs the memory address of the variable in order to assign it a value. Therefore, we write '&amp;firstName' as the parameter.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">var</span> firstName <span class="hljs-keyword">string</span>
    fmt.Scan(&amp;firstName)
}
</code></pre>
<p>Lastly, we want to output a greeting to the screen. We can do this with the 'Println()' function. Note that this function is the exact same as 'Print()' but it adds a newline character to the end of the outputted string.</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">var</span> firstName <span class="hljs-keyword">string</span>
    fmt.Scan(&amp;firstName)
    fmt.Println(<span class="hljs-string">"Hello"</span>, firstName)
}
</code></pre>
<p>With the script finished, you can run it with 'go run main.go'.</p>
]]></content:encoded></item><item><title><![CDATA[How to Declare a Variable in Go]]></title><description><![CDATA[Variables are super important for coding, and declaring one is one of the first things you should know how to do when learning a new programming language.
In Go, this is very easy to do. You simply use the keyword 'var'. To declare a variable without...]]></description><link>https://blog.gotechwithalissa.com/how-to-declare-a-variable-in-go</link><guid isPermaLink="true">https://blog.gotechwithalissa.com/how-to-declare-a-variable-in-go</guid><category><![CDATA[Go Language]]></category><category><![CDATA[variables]]></category><category><![CDATA[variable declaration]]></category><category><![CDATA[#VariableAssignment]]></category><dc:creator><![CDATA[Alissa Lozhkin]]></dc:creator><pubDate>Sun, 30 Jun 2024 18:51:49 GMT</pubDate><content:encoded><![CDATA[<p>Variables are super important for coding, and declaring one is one of the first things you should know how to do when learning a new programming language.</p>
<p>In Go, this is very easy to do. You simply use the keyword 'var'. To declare a variable without assigning a value to it right away, you can write the following:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> abc <span class="hljs-keyword">string</span>
</code></pre>
<p>The code above defines a string variable called 'abc'.</p>
<p>We can just as well use this syntax to assign a value to the variable:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> abc <span class="hljs-keyword">string</span> = <span class="hljs-string">"Hello"</span>
</code></pre>
<p>The code above defines a string variable called 'abc' with the value "Hello."</p>
<p>You can also declare and assign without specifying the datatype of the variable by writing something like this:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> abc = <span class="hljs-string">"Hello"</span>
</code></pre>
<p>In the code above, it is left to the compiler to figure out the datatype of the variable 'abc'.</p>
<p>There is another syntax that can be used for the declaring and assigning of a variable:</p>
<pre><code class="lang-go">abc := <span class="hljs-string">"Hello"</span>
</code></pre>
<p>The ':=' notation is used instead of 'var'. Note that this notation can only be used when first declaring a variable. If you want to assign 'abc' another value later on, you should use '=' and not ':='.</p>
<p>One final note on variables: they are designed to be mutable so you can change the value of them. However, the datatype of the variable cannot be changed.</p>
]]></content:encoded></item><item><title><![CDATA[How to Print "Hello World" Using Go]]></title><description><![CDATA[Go is a language that is increasing in popularity, and for good reason. With Python's easy-to-understand syntax and C's efficiency, more and more companies are starting to use Go as a programming language in their software. As a software developer, G...]]></description><link>https://blog.gotechwithalissa.com/how-to-print-hello-world-using-go</link><guid isPermaLink="true">https://blog.gotechwithalissa.com/how-to-print-hello-world-using-go</guid><category><![CDATA[Go Language]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[Hello World]]></category><category><![CDATA[Computer Science]]></category><dc:creator><![CDATA[Alissa Lozhkin]]></dc:creator><pubDate>Mon, 05 Feb 2024 17:50:37 GMT</pubDate><content:encoded><![CDATA[<p>Go is a language that is increasing in popularity, and for good reason. With Python's easy-to-understand syntax and C's efficiency, more and more companies are starting to use Go as a programming language in their software. As a software developer, Go is a great programming language to know, and the best way to start learning a language is to start off with the absolute basics. This tutorial will teach you how to get started with Go by writing a script to print "Hello World."</p>
<p>Starting off with a blank file, we first have to import a library called 'fmt' which stands for 'format'. This module has formatted I/O functions that allow for the printing/scanning of user input.</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>
</code></pre>
<p>The code is going to reside in a function called 'main', and we can define this function like this:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {}
</code></pre>
<p>Inside this function, we can use the 'Println' function found in the 'fmt' library to print 'Hello World'.</p>
<pre><code class="lang-go">fmt.Println(<span class="hljs-string">"Hello World"</span>)
</code></pre>
<p>And so the final script is this:</p>
<pre><code class="lang-go"><span class="hljs-keyword">import</span> <span class="hljs-string">"fmt"</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    fmt.Println(<span class="hljs-string">"Hello World"</span>)
}
</code></pre>
<p>Congratulations, you have written your first script in GO! After writing the script, we would like to execute it, and this can be done through the following steps.</p>
<p>Let's say the 'Hello World' script exists inside a file called 'main.go' as shown below. Note that at line 1, we specify that this file belongs to the package 'main'. This is because every file written in Go must belong to some sort of package, otherwise Go will give an error.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1706744896444/76ada602-47bf-4e91-a642-fce565d6b967.png" alt class="image--center mx-auto" /></p>
<p>In the terminal, we can then write the command 'go run main.go' to execute the script. After writing this command, you will see 'Hello World' outputted in the terminal. You have now successfully written and executed a Go script!</p>
]]></content:encoded></item><item><title><![CDATA[How to setup Mattermost on Ubuntu 20.04 with PostgreSQL]]></title><description><![CDATA[Mattermost is a self-hosted and open source alternative to Slack. It is a messaging platform that uses either PostgreSQL or MySQL in the backend (PostgreSQL will be used in this tutorial). 
This tutorial will be taking you through the process of sett...]]></description><link>https://blog.gotechwithalissa.com/how-to-setup-mattermost-on-ubuntu-2004-with-postgresql</link><guid isPermaLink="true">https://blog.gotechwithalissa.com/how-to-setup-mattermost-on-ubuntu-2004-with-postgresql</guid><category><![CDATA[Linux]]></category><dc:creator><![CDATA[Alissa Lozhkin]]></dc:creator><pubDate>Sun, 29 Aug 2021 18:02:02 GMT</pubDate><content:encoded><![CDATA[<p>Mattermost is a self-hosted and open source alternative to Slack. It is a messaging platform that uses either PostgreSQL or MySQL in the backend (PostgreSQL will be used in this tutorial). </p>
<p>This tutorial will be taking you through the process of setting up Mattermost on Ubuntu 20.04. The process is not complicated, and I have added explanations (and things you should note) for each step to help you through it :)</p>
<p>Before starting, you should first update and upgrade Ubuntu.</p>
<pre><code>sudo apt <span class="hljs-keyword">update</span>
sudo apt updgrade
</code></pre><p>After, you should reboot the system by running: </p>
<pre><code>reboot
</code></pre><p>First, you want to download PostgreSQL by running the command below:</p>
<pre><code><span class="hljs-attribute">sudo</span> apt -y install postgresql postgresql-contrib
</code></pre><p>Once it finishes downloading, run the following command to login into the PostgreSQL database:</p>
<pre><code>sudo <span class="hljs-comment">--login --user postgres</span>
</code></pre><p>Next, what you want to do is write a series of commands. 
<em>*Note, copy all commands as is, so make sure the commands are in uppercase and that there is a ';' at the end of each statement (I left both parts out on my first attempt at running mattermost… it didn't work :p).</em></p>
<pre><code>psql
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">DATABASE</span> mattermost;
</code></pre><p>After running the command above, you should see printed on the command-line that the database was created. You can run <code>\l</code> to see all databases, and you should see the mattermost database there.</p>
<pre><code><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">USER</span> &lt;username&gt; <span class="hljs-keyword">WITH</span> <span class="hljs-keyword">PASSWORD</span> <span class="hljs-string">'&lt;password&gt;'</span>;
</code></pre><p>You should see that the role was created. Use your own username and password, and make sure you remember the username and password you chose for the user, as it will be used for future configurations.</p>
<pre><code><span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">ALL</span> <span class="hljs-keyword">PRIVILEGES</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">DATABASE</span> mattermost <span class="hljs-keyword">to</span> &lt;username&gt;;
\q
</code></pre><p>The last command exits the psql CLI. </p>
<p>Run the following command to exit the PostgreSQL account: </p>
<pre><code><span class="hljs-keyword">exit</span>
</code></pre><p>Next, we want to add a new user to run our mattermost instance (the user is named mattermost):</p>
<pre><code>sudo useradd <span class="hljs-comment">--system --user-group mattermost</span>
</code></pre><p>We are then going to install Mattermost by running the following command (here, version 5.37.0 is being installed, check the most recent version of Mattermost at the time you are installing it).</p>
<pre><code><span class="hljs-attribute">wget</span> https://releases.mattermost.com/<span class="hljs-number">5</span>.<span class="hljs-number">37</span>.<span class="hljs-number">0</span>/mattermost-<span class="hljs-number">5</span>.<span class="hljs-number">37</span>.<span class="hljs-number">0</span>-linux-amd<span class="hljs-number">64</span>.tar.gz
</code></pre><p>You want to then extract the archive and move it to the /opt folder</p>
<pre><code><span class="hljs-attribute">tar</span> xvf mattermost-<span class="hljs-number">5</span>.<span class="hljs-number">37</span>.<span class="hljs-number">0</span>-linux-amd<span class="hljs-number">64</span>.tar.gz
<span class="hljs-attribute">sudo</span> mv mattermost /opt
</code></pre><p>You should then create the storage directory for files that are posted to Mattermost</p>
<pre><code>sudo mkdir /opt/mattermost/<span class="hljs-keyword">data</span>
</code></pre><p>Give the mattermost user ownership and permission to the directory:</p>
<pre><code><span class="hljs-selector-tag">sudo</span> <span class="hljs-selector-tag">chown</span> <span class="hljs-selector-tag">-R</span> <span class="hljs-selector-tag">mattermost</span><span class="hljs-selector-pseudo">:mattermost</span> /<span class="hljs-selector-tag">opt</span>/<span class="hljs-selector-tag">mattermost</span>
</code></pre><p>Give the write permission to the mattermost user as well:</p>
<pre><code>sudo <span class="hljs-keyword">chmod</span> -R g+w /opt/mattermost
</code></pre><p>Next, you have to go into the configuration file that is stored in the directory:</p>
<pre><code>sudo nano /opt/mattermost/config/config.json
</code></pre><p>In this file, you'll find keys with certain key-value pairs. There are four values you should change in your configuration of Mattermost. 
<em>* Note, I am attempting to run Mattermost locally, and so that is why I am using 'localhost:8065'. You should change the values below depending on what domain name you want Mattermost to run on.</em></p>
<pre><code>[<span class="hljs-string">"ServiceSettings"</span>][<span class="hljs-symbol">"SiteURL"</span>] = "http://localhost:8065"

[<span class="hljs-string">"ServiceSettings"</span>][<span class="hljs-symbol">"ListenAddress"</span>] = "localhost:8065"
</code></pre><p>Next, you want to rewrite a value so that Mattermost is using PostgreSQL in the backend. </p>
<pre><code>[<span class="hljs-string">"SqlSettings"</span>][<span class="hljs-symbol">"DriverName"</span>] = "postgres"
</code></pre><p>Make sure you put in the value below for the "Datasource" key. Make sure to put in your username and password where prompted. Also, make sure to keep the port in this URL as 5432 because otherwise, it'll give you a "failing to ping database" message after starting Mattermost. </p>
<pre><code>[<span class="hljs-string">"SqlSettings"</span>][<span class="hljs-symbol">"DataSource"</span>] = "postgres://<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">username</span>&gt;</span></span>:<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">password</span>&gt;</span></span>@localhost:5432/mattermost?sslmode=disable\u0026connect<span class="hljs-emphasis">_timeout=10"</span>
</code></pre><p>You should save and close the file after modifying the values. </p>
<p>Next, you have to go into the mattermost.service file by running the command below.</p>
<pre><code>sudo nano /etc/systemd/<span class="hljs-keyword">system</span>/mattermost.service
</code></pre><p>Copy and paste the below code snippet into the file. </p>
<pre><code><span class="hljs-section">[Unit]</span>
<span class="hljs-attr">Description</span>=Mattermost
<span class="hljs-attr">After</span>=network.target
<span class="hljs-attr">After</span>=postgresql.service
<span class="hljs-attr">Requires</span>=postgresql.service

<span class="hljs-section">[Service]</span>
<span class="hljs-attr">Type</span>=notify
<span class="hljs-attr">ExecStart</span>=/opt/mattermost/bin/mattermost
<span class="hljs-attr">TimeoutStartSec</span>=<span class="hljs-number">3600</span>
<span class="hljs-attr">Restart</span>=always
<span class="hljs-attr">RestartSec</span>=<span class="hljs-number">10</span>
<span class="hljs-attr">WorkingDirectory</span>=/opt/mattermost
<span class="hljs-attr">User</span>=mattermost
<span class="hljs-attr">Group</span>=mattermost
<span class="hljs-attr">LimitNOFILE</span>=<span class="hljs-number">49152</span>

<span class="hljs-section">[Install]</span>
<span class="hljs-attr">WantedBy</span>=multi-user.target
</code></pre><p>Save and close the file. </p>
<p>Then run the following commands to start and enable Mattermost. </p>
<pre><code>sudo systemctl daemon-reload
sudo systemctl <span class="hljs-keyword">start</span> mattermost.service
sudo systemctl <span class="hljs-keyword">enable</span> mattermost.service
</code></pre><p>After running the commands above, you can check the status of Mattermost by running:</p>
<pre><code><span class="hljs-selector-tag">sudo</span> <span class="hljs-selector-tag">systemctl</span> <span class="hljs-selector-tag">mattermost</span><span class="hljs-selector-class">.service</span>
</code></pre><p>Outputted onto the screen, you can see the status of Mattermost. If it is running (active), then you can navigate to Mattermost using your own domain name and you should see Mattermost running there!</p>
]]></content:encoded></item></channel></rss>