<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Go - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Go - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 26 May 2026 22:47:45 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/go-cjffccfnf0024tjs1mcwab09t/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ What are Variables and Constants in Go? Explained With Examples ]]>
                </title>
                <description>
                    <![CDATA[ Variables and constants are fundamental concepts in most programming languages. They are the building blocks for storing and managing data. In this article, we'll take a look at how variables and constant work in Go. Table of contents: What are Vari... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/variables-and-constants-in-go/</link>
                <guid isPermaLink="false">66c2f3bae041c8717c0645d2</guid>
                
                    <category>
                        <![CDATA[ Go ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Temitope Oyedele ]]>
                </dc:creator>
                <pubDate>Mon, 19 Aug 2024 07:26:50 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1724052347929/f54eba57-fa4b-4b81-821e-41826d592933.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Variables and constants are fundamental concepts in most programming languages. They are the building blocks for storing and managing data.</p>
<p>In this article, we'll take a look at how variables and constant work in Go.</p>
<h2 id="heading-table-of-contents">Table of contents:</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-are-variables">What are Variables?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-a-variable-in-go">How to Create a Variable</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-explicit-declaration">Explicit Declaration</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-shorthand-variable-declaration">Shorthand Variable Declaration</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-multiple-variable-declarations">Multiple Variable Declarations</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-zero-values">Zero Values</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-a-variable-scope">What is a Variable Scope</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-naming-conventions-in-go">Naming Conventions in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-constants-in-go">What are Constants in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-declare-constants-in-go">How to Declare Constants in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-types-of-constants-in-go">Type of Constants in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-thats-a-wrap">That's a Wrap</a></p>
</li>
</ul>
<h2 id="heading-what-are-variables">What are Variables ?</h2>
<p>A variable is a storage location identified by a name (or identifier) that holds a value. This value can change (or vary) during a program's execution. This is why it's called a variable.</p>
<p>For example:</p>
<pre><code class="lang-go">myName := “temitope”

fmt.Println(myName)

myName:= ”oyedele”

fmt.Println(myName)
</code></pre>
<p>We created a variable with an identifier of <code>myName</code> which holds a string value.</p>
<p>If you noticed, we changed the value to another string, and we can do that multiple times because variables are allowed to do that.</p>
<p>Variables allow you to store data, which can be of different types, such as integers, floating-point numbers, strings, or objects.</p>
<h2 id="heading-how-to-create-a-variable-in-go">How to Create a Variable in Go</h2>
<p>There are two primary ways to create a variable in Go, explicit declaration and shorthand declaration.</p>
<h3 id="heading-explicit-declaration">Explicit Declaration</h3>
<p>This is the traditional way to create a variable in Go. It works by using the <code>var</code> keyword and declaring the variable’s type, making your code more readable and clear.</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> age <span class="hljs-keyword">int</span> = <span class="hljs-number">25</span>

    <span class="hljs-keyword">var</span> name <span class="hljs-keyword">string</span> = <span class="hljs-string">"Temitope"</span>

    <span class="hljs-keyword">var</span> height <span class="hljs-keyword">float64</span> = <span class="hljs-number">5.7</span>

    fmt.Println(age, name, height)

}
</code></pre>
<p>You can see that, for each variable, we declared its datatype before assigning a value to it.</p>
<pre><code class="lang-plaintext">output:
25 Temitope 5.7
</code></pre>
<p>The <code>var</code> keyword and data type can also be used without having an initial value:</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> age <span class="hljs-keyword">int</span>
    <span class="hljs-keyword">var</span> name <span class="hljs-keyword">string</span>
    <span class="hljs-keyword">var</span> height <span class="hljs-keyword">float64</span>

    age = <span class="hljs-number">25</span>
    name = <span class="hljs-string">"Temitope"</span>
    height = <span class="hljs-number">5.7</span>

    fmt.Println(age, name, height)
}
</code></pre>
<p>This way, the variables are declared first without an initial value. They are then assigned values later in the code. You'll still have the same output as the first.</p>
<h3 id="heading-shorthand-variable-declaration">Shorthand Variable Declaration</h3>
<p>The shorthand variable declaration syntax (<code>:=</code>) is a more concise way to declare variables. This method allows you to declare and initialize a variable in a single line without explicitly stating its type, as the type is inferred from the value assigned.</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> {

    age := <span class="hljs-number">25</span>

    name := <span class="hljs-string">"Temitope"</span>

    height := <span class="hljs-number">5.7</span>

    fmt.Println(age, name, height)

}
</code></pre>
<p>Here, each variable was declared alongside its value, with Go inferring the datatype. For example, <code>age</code> was declared and initialized with a value of 25, and Go inferred its type as <code>int</code>. <code>name</code> was declared with the value "Temitope", and Go inferred its type as <code>string</code>. Lastly, <code>height</code> was declared with 5.7, and Go inferred its type as <code>float64</code>.</p>
<pre><code class="lang-plaintext">output:
25 Temitope 5.7
</code></pre>
<p>One of the drawbacks of the shorthand variable declaration is that you can only use it inside of a function.</p>
<h2 id="heading-multiple-variable-declarations">Multiple Variable Declarations</h2>
<p>You can declare and initialize multiple variables on the same line by separating each variable with a comma. This approach is simple and straightforward. it is commonly used when the variables are related or when you want to initialize them together. For example:</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> age, height <span class="hljs-keyword">int</span> = <span class="hljs-number">25</span>, <span class="hljs-number">180</span>

    <span class="hljs-keyword">var</span> name, city <span class="hljs-keyword">string</span> = <span class="hljs-string">"Temitope"</span>, <span class="hljs-string">"New York"</span>

    fmt.Println(age, height)

    fmt.Println(name, city)
}
</code></pre>
<p>Here, the variable <code>age</code> and <code>height</code> are both declared as integers and initialized with the values 25 and 180, respectively. Variable <code>name</code> and <code>city</code> are also both declared as strings and initialized with "Temitope" and "New York":</p>
<pre><code class="lang-plaintext">Output:
25 180
Temitope New York
</code></pre>
<p>You can also declare multiple variables in a block like so:</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> (
        age <span class="hljs-keyword">int</span> = <span class="hljs-number">25</span>

        name <span class="hljs-keyword">string</span> = <span class="hljs-string">"Temitope"</span>

        height <span class="hljs-keyword">int</span> = <span class="hljs-number">180</span>

        city <span class="hljs-keyword">string</span> = <span class="hljs-string">"New York"</span>
    )

    fmt.Println(age, name, height, city)

}
</code></pre>
<p>Here, the variables <code>age</code>, <code>name</code>, <code>height</code>, and <code>city</code> are declared within a single var block, with each variable getting its own line.</p>
<pre><code class="lang-plaintext">Output:
25 Temitope 180 New York
</code></pre>
<h3 id="heading-zero-values">Zero Values</h3>
<p>When variables are declared without being initialized, they are assigned zero values by default. These values differ depending on the type of variable. Below is an example of how you can declare default values:</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> intValue <span class="hljs-keyword">int</span>

    <span class="hljs-keyword">var</span> floatValue <span class="hljs-keyword">float64</span>

    <span class="hljs-keyword">var</span> boolValue <span class="hljs-keyword">bool</span>

    <span class="hljs-keyword">var</span> stringValue <span class="hljs-keyword">string</span>

    <span class="hljs-keyword">var</span> ptrValue *<span class="hljs-keyword">int</span>

    <span class="hljs-keyword">var</span> sliceValue []<span class="hljs-keyword">int</span>

    <span class="hljs-keyword">var</span> mapValue <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">int</span>

    fmt.Println(<span class="hljs-string">"Zero values:"</span>)

    fmt.Println(<span class="hljs-string">"int:"</span>, intValue)

    fmt.Println(<span class="hljs-string">"float64:"</span>, floatValue)

    fmt.Println(<span class="hljs-string">"bool:"</span>, boolValue)

    fmt.Println(<span class="hljs-string">"string:"</span>, stringValue)

    fmt.Println(<span class="hljs-string">"pointer:"</span>, ptrValue)

    fmt.Println(<span class="hljs-string">"slice:"</span>, sliceValue)

    fmt.Println(<span class="hljs-string">"map:"</span>, mapValue)

}
</code></pre>
<p>In the code above, here’s what’s going to happen:</p>
<ul>
<li><p>The integer <code>intValue</code> will be given the zero value 0.</p>
</li>
<li><p>The floating-point number <code>floatValue</code> will be given the zero value 0.</p>
</li>
<li><p>The Boolean <code>boolValue</code> will be given the zero value <code>false</code>.</p>
</li>
<li><p>The string <code>stringValue</code> will be given the zero value "" (empty string).</p>
</li>
<li><p>The pointer <code>ptrValue</code>, slice <code>sliceValue</code>, and map <code>mapValue</code> will all be given the zero value <code>nil</code>.</p>
</li>
</ul>
<p>Output:</p>
<pre><code class="lang-plaintext">Output:
Zero values:
int: 0
float64: 0
bool: false
string: 
pointer: &lt;nil&gt;
slice: []
map: map[]
</code></pre>
<h3 id="heading-what-is-a-variable-scope">What is a Variable Scope?</h3>
<p>Variables can be declared either globally or locally. The scope of a variable determines where it can be accessed and modified within your code.</p>
<p>Global variables are declared outside of any function, typically at the top of a file, and they can be accessed by any function within the same package.  Here’s an example:</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-keyword">var</span> globalCounter <span class="hljs-keyword">int</span> = <span class="hljs-number">0</span>

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

    globalCounter++

}

<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">"Initial Counter:"</span>, globalCounter)

    incrementCounter()

    fmt.Println(<span class="hljs-string">"After Increment:"</span>, globalCounter)

}
</code></pre>
<p>In the above example, <code>globalCounter</code> is the global variable, and it is accessible by both the <code>incrementCounter</code> function and the <code>main</code> function.</p>
<p>Also, the value of <code>globalCounter</code> persists across function calls. This means that whatever change is made to it in one function affects its value in other parts of the program.</p>
<p>Local variables, on the other hand, are declared within a function or a block and are only accessible within that specific function or block. They are created when the function or block is executed and destroyed once it is completed. For example:</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">incrementCounter</span><span class="hljs-params">()</span></span> {

    localCounter := <span class="hljs-number">0</span>

    localCounter++

    fmt.Println(<span class="hljs-string">"Local Counter:"</span>, localCounter)

}

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

    incrementCounter()

    incrementCounter()

}
</code></pre>
<p>In the code above, we have the <code>localCounter</code> as the local variable inside the <code>incrementCounter</code> function. Each time <code>incrementCounter</code> is called, a new <code>localCounter</code> is created, initialized to 0, and incremented.</p>
<p>The value of <code>localCounter</code> does not persist between function calls, so it cannot affect any part of a program when a change is made to the function.</p>
<h2 id="heading-naming-conventions-in-go">Naming Conventions in Go</h2>
<p>Proper naming of variables is crucial for writing clean, readable, and maintainable code. Go has some specific conventions and rules for naming variables. Below are some of them:</p>
<ul>
<li><p><strong>Use descriptive names:</strong>  Use names that clearly describe the purpose or content of the variable. For example, instead of using vague names like x or y, use names like <code>age</code>, <code>totalPrice</code>, or <code>userName</code> that clearly convey what the variable represents.</p>
</li>
<li><p><strong>Use CamelCase for Multi-Word Names:</strong> In Go, it's common practice to use camelCase for variable names that consist of multiple words. The first word is lowercase, and the first letter of each subsequent word is capitalized.</p>
</li>
<li><p><strong>Avoid Using Underscores:</strong> Unlike some other languages, Go prefers camelCase over using underscores to separate words in variable names. Stick to camelCase to adhere to Go’s idiomatic style.</p>
</li>
<li><p><strong>Use Short Names for Short-Lived Variables:</strong> For short-lived variables, such as loop counters or indices, it's acceptable to use short names like i, j, or k.</p>
</li>
</ul>
<h2 id="heading-what-are-constants-in-go">What are Constants in Go?</h2>
<p>Constants are immutable values defined at compile time that cannot be modified throughout the program's execution. They are useful for defining values that are known ahead of time and will remain the same.</p>
<p>Imagine you're building an online store where the standard shipping fee is always $10. You can declare it as a constant, so you can use it throughout your program whenever shipping charges need to be applied. If the shipping rates change, you only need to update the value in one place.</p>
<h2 id="heading-how-to-declare-constants-in-go">How to Declare Constants in Go</h2>
<p>You can declare constants using the <code>const</code> keyword, followed by the name, the type (optional if the value implies the type), and the value of the constant. Here’s how:</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">const</span> pi <span class="hljs-keyword">float64</span> = <span class="hljs-number">3.14159</span>

    <span class="hljs-keyword">const</span> greeting <span class="hljs-keyword">string</span> = <span class="hljs-string">"Hello, World!"</span>

    fmt.Println(<span class="hljs-string">"Pi:"</span>, pi)

    fmt.Println(<span class="hljs-string">"Greeting:"</span>, greeting)

}
</code></pre>
<p>If you try to change a constant after being declared, then you’ll get a compile-time error.</p>
<h2 id="heading-types-of-constants-in-go">Types of Constants in Go</h2>
<p>Constants can be categorized as either typed or untyped. Both types of constants serve the same purpose. They provide fixed, immutable values throughout the program. However, they differ in how Go handles their types and how flexible they are when used.</p>
<p>Untyped constants are not assigned a type unless they are used in a context that requires a type. When you declare an untyped constant, Go will infer the type at the point where the constant is used. This makes untyped constants more flexible because they can be used in a number of settings without requiring type conversion.</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-keyword">const</span> gravity = <span class="hljs-number">9.81</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> height <span class="hljs-keyword">int</span> = <span class="hljs-number">10</span>

    <span class="hljs-keyword">var</span> acceleration <span class="hljs-keyword">float64</span> = gravity * <span class="hljs-keyword">float64</span>(height)

    fmt.Println(<span class="hljs-string">"Acceleration:"</span>, acceleration)

}
</code></pre>
<p>Here, <code>gravity</code> is the untyped constant. This means Go can infer its type based on how it is used. When <code>gravity</code> is used in a calculation with a <code>float64</code>, Go will automatically treat it as a <code>float64</code>.</p>
<p>Unlike untyped constants, the typed constants have an explicitly declared type. This means they can only be used in contexts that match that type or can be converted to a compatible type. Typed constants are stricter, ensuring that the value is always treated as the specific type it was declared with.</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-keyword">const</span> speedOfLight <span class="hljs-keyword">int</span> = <span class="hljs-number">299792458</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> distance <span class="hljs-keyword">int</span> = speedOfLight * <span class="hljs-number">2</span>

    fmt.Println(<span class="hljs-string">"Distance:"</span>, distance)

}
</code></pre>
<p>Here, <code>speedOfLight</code> is the typed constant with the type <code>int</code>.</p>
<p>It can only be used in operations with other <code>int</code> values or converted explicitly to a different type.</p>
<h2 id="heading-thats-a-wrap">That’s a Wrap</h2>
<p>In this article, we took a look at what variables and constants are and how to declare them in Go.</p>
<p>Variables and constants are critical tools in programming. They allow developers to efficiently manage and manipulate data. When you understand how to use them, you can improve the quality of your code. </p>
<p>Please share if you found this helpful.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
