<?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[ Pedro - 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[ Pedro - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 21 May 2026 04:57:29 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/bertao/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ What is New in Go 1.25? Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ Go 1.25 isn’t a flashy release with big syntax changes. Instead, it’s a practical one: it fixes long-standing pitfalls, improves runtime safety, adds smarter tooling, and introduces a powerful new JSON engine. These are the kind of updates that make ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-new-in-go/</link>
                <guid isPermaLink="false">68bb7a5a881edef26f226cde</guid>
                
                    <category>
                        <![CDATA[ golang ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Go Language ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Pedro ]]>
                </dc:creator>
                <pubDate>Sat, 06 Sep 2025 00:03:38 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1757071558420/9a83b3fb-dbea-4d38-96ca-460bf20c213d.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Go 1.25 isn’t a flashy release with big syntax changes. Instead, it’s a practical one: it fixes long-standing pitfalls, improves runtime safety, adds smarter tooling, and introduces a powerful new JSON engine. These are the kind of updates that make your day-to-day coding experience smoother and your production apps more reliable.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-table-of-contents">Table of Contents</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-goodbye-core-types">Goodbye “Core Types”</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-safer-nil-pointer-handling">Safer Nil-Pointer Handling</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-dwarf-v5-debug-info-by-default">DWARF v5 Debug Info by Default</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-testingsynctest-is-stable">testing/synctest is Stable</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-experimental-encodingjsonv2">Experimental encoding/json/v2</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-tooling-improvements">Tooling Improvements</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-runtime-improvements">Runtime Improvements</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-flight-recorder-api">Flight Recorder API</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-platform-updates">Platform Updates</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-key-takeaways">Key Takeaways</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-sources">Sources</a></p>
</li>
</ul>
<p>Let’s walk through the highlights.</p>
<h2 id="heading-goodbye-core-types">Goodbye “Core Types”</h2>
<p>Core types were introduced in Go 1.18, where, <a target="_blank" href="https://go.dev/blog/coretypes">according to the documentation</a>, “a core type is an abstract construct that was introduced for expediency and to simplify dealing with generic operands”. For example, we have:</p>
<ul>
<li><p>If a type is not a type parameter, its core type is simply its underlying type.</p>
</li>
<li><p>If the type is a type parameter, its core type exists only if all types in its type set share the same underlying type. In such cases, that common underlying type becomes the core type. Otherwise, no core type exists.</p>
</li>
</ul>
<p>In Go 1.25, the team removed the notion of core types from the spec and instead defined each feature with explicit rules for generics, simplifying the language while keeping everything fully backward-compatible. For example, operations like addition on a generic type are now described directly in terms of type sets, without needing to reference core types.</p>
<h2 id="heading-safer-nil-pointer-handling">Safer Nil-Pointer Handling</h2>
<p>A bug introduced in Go 1.21 sometimes prevented <code>nil</code> pointer panics from triggering. That’s now fixed. If you dereference a <code>nil</code>, it will reliably panic. Previously, the behavior was:</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-string">"os"</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">// Try to open a file that doesn't exist.</span>
    <span class="hljs-comment">// os.Open returns a nil file handle and a non-nil error.</span>
    f, err := os.Open(<span class="hljs-string">"does-not-exist.txt"</span>) <span class="hljs-comment">// f is nil, err is non-nil</span>
    fmt.Println(<span class="hljs-string">"err:"</span>, err) <span class="hljs-comment">// Prints the error</span>

    <span class="hljs-comment">// Buggy behavior explanation:</span>
    <span class="hljs-comment">// The program uses f.Name() before checking the error.</span>
    <span class="hljs-comment">// Since f is nil, this call panics at runtime.</span>
    <span class="hljs-comment">// Older Go versions (1.21–1.24) sometimes let this run,</span>
    fmt.Println(<span class="hljs-string">"name:"</span>, f.Name())
}
</code></pre>
<p>In Go 1.21–1.24, a compiler bug sometimes suppressed the panic in the code above and made it look like your program was "fine." In Go 1.25, it will no longer run successfully. With the fixed behavior, 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">"fmt"</span>
    <span class="hljs-string">"os"</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">// Try to open a file that doesn't exist.</span>
    <span class="hljs-comment">// os.Open returns a nil file handle and a non-nil error.</span>
    f, err := os.Open(<span class="hljs-string">"does-not-exist.txt"</span>) 
    fmt.Println(<span class="hljs-string">"err:"</span>, err) <span class="hljs-comment">// Prints an error</span>

    <span class="hljs-comment">// This now reliably panics, since f is nil and you’re dereferencing it.</span>
    fmt.Println(<span class="hljs-string">"name:"</span>, f.Name())
}
</code></pre>
<p>The key difference is that it now throws a panic, making the behavior more predictable.</p>
<h2 id="heading-dwarf-v5-debug-info-by-default">DWARF v5 Debug Info by Default</h2>
<p>DWARF is a standardized format for storing debugging information inside compiled binaries.<br>Think of it as a map that tells debuggers (like <code>gdb</code>, <code>dlv</code> for Go, or IDEs like VS Code/GoLand) how your compiled program relates back to your source code.</p>
<p>Go 1.25 now uses DWARF v5 for debug information. The result is smaller binaries and faster linking. If you need older tooling compatibility, you can disable it with <code>GOEXPERIMENT=nodwarf5</code>.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Normal build (DWARF v5 enabled automatically):</span>
go build ./...

<span class="hljs-comment"># If you have tooling that doesn’t support DWARF v5, you can disable it:</span>
GOEXPERIMENT=nodwarf5 go build ./...
</code></pre>
<h2 id="heading-testingsynctest-is-stable">testing/synctest is Stable</h2>
<p>Testing concurrent code just got easier. The new <a target="_blank" href="https://pkg.go.dev/testing/synctest"><code>testing/synctest</code></a> package lets you run concurrency tests in a controlled environment where goroutines and time are deterministic.</p>
<pre><code class="lang-go"><span class="hljs-comment">// Run with: go test</span>
<span class="hljs-keyword">package</span> counter

<span class="hljs-keyword">import</span> (
    <span class="hljs-string">"testing"</span>
    <span class="hljs-string">"testing/synctest"</span>
)

<span class="hljs-comment">// Counter is a simple struct holding an integer.</span>
<span class="hljs-comment">// It has methods to increment the count and retrieve the value.</span>
<span class="hljs-keyword">type</span> Counter <span class="hljs-keyword">struct</span>{ n <span class="hljs-keyword">int</span> }

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(c *Counter)</span> <span class="hljs-title">Inc</span><span class="hljs-params">()</span></span> { c.n++ } <span class="hljs-comment">// Increase counter by 1</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(c *Counter)</span> <span class="hljs-title">N</span><span class="hljs-params">()</span> <span class="hljs-title">int</span></span> { <span class="hljs-keyword">return</span> c.n } <span class="hljs-comment">// Return the current count</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">TestCounter_Inc_Deterministic</span><span class="hljs-params">(t *testing.T)</span></span> {
    <span class="hljs-comment">// synctest.New creates a special deterministic test environment ("bubble").</span>
    <span class="hljs-comment">// Inside this bubble, goroutines are scheduled in a controlled way,</span>
    <span class="hljs-comment">// so the test result is always predictable (no race conditions).</span>
    st := synctest.New()
    <span class="hljs-keyword">defer</span> st.Done() <span class="hljs-comment">// Cleanup: always close the test bubble at the end.</span>

    c := &amp;Counter{}
    <span class="hljs-keyword">const</span> workers = <span class="hljs-number">10</span>

    <span class="hljs-comment">// Start 10 goroutines inside the synctest bubble.</span>
    <span class="hljs-comment">// Each goroutine calls c.Inc(), incrementing the counter.</span>
    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; workers; i++ {
        st.Go(<span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">()</span></span> { c.Inc() })
    }

    <span class="hljs-comment">// Run the bubble until all goroutines are finished.</span>
    <span class="hljs-comment">// This ensures deterministic completion of the test.</span>
    st.Run()

    <span class="hljs-comment">// Verify the result: counter should equal number of goroutines (10).</span>
    <span class="hljs-comment">// If not, fail the test with a clear message.</span>
    <span class="hljs-keyword">if</span> got, want := c.N(), workers; got != want {
        t.Fatalf(<span class="hljs-string">"got %d, want %d"</span>, got, want)
    }
}
</code></pre>
<p>With the new <code>testing/synctest</code>, tests ensure a deterministic, flake-free run, so the counter always ends up at 10.</p>
<h2 id="heading-experimental-encodingjsonv2">Experimental encoding/json/v2</h2>
<p>A brand-new JSON engine is available under the <code>GOEXPERIMENT=jsonv2</code> flag. It’s faster, more efficient, and includes a streaming-friendly <code>jsontext</code> package. Even better, the old <code>encoding/json</code> can piggyback on the new engine—so you get performance boosts without breaking old code.</p>
<h2 id="heading-tooling-improvements">Tooling Improvements</h2>
<ul>
<li><p><code>go vet</code> now catches common mistakes like incorrect <code>sync.WaitGroup.Add</code> usage and unsafe host:port handling.</p>
</li>
<li><p><code>go doc -http</code> serves documentation locally in your browser.</p>
</li>
<li><p><code>go build -asan</code> can detect memory leaks automatically.</p>
</li>
</ul>
<p>These small upgrades add up to a smoother dev workflow.</p>
<h2 id="heading-runtime-improvements">Runtime Improvements</h2>
<p>Go now runs smarter inside containers. On Linux, it automatically detects how many CPUs the container is allowed to use and adjusts itself. There’s also a new experimental garbage collector called <em>greenteagc</em>, which can make memory cleanup up to 40% faster in some cases.</p>
<h2 id="heading-flight-recorder-api">Flight Recorder API</h2>
<p>Have you ever wished you could see exactly what your Go application was doing when something went wrong—like when a request suddenly takes 10 seconds instead of 100 milliseconds, or your app mysteriously starts using too much CPU? By the time you notice, it’s usually too late to debug because the issue has already passed. Go’s new FlightRecorder feature solves this by continuously capturing a lightweight runtime trace in memory, allowing your program to snapshot the last few seconds of activity to a file whenever a significant event occurs.</p>
<h2 id="heading-platform-updates">Platform Updates</h2>
<ul>
<li><p>macOS 12 (Monterey) is now the minimum supported version.</p>
</li>
<li><p>Windows/ARM 32-bit support is deprecated and will be removed in Go 1.26.</p>
</li>
<li><p>RISC-V and Loong64 gained new capabilities like plugin builds and race detection.</p>
</li>
</ul>
<h2 id="heading-key-takeaways">Key Takeaways</h2>
<ul>
<li><p><strong>Safer by default</strong>: no more silent nil pointer bugs, better panic reporting.</p>
</li>
<li><p><strong>Faster builds &amp; runtime</strong>: DWARF v5 debug info, container-aware scheduling, and optional GC improvements.</p>
</li>
<li><p><strong>Better tooling</strong>: smarter <code>go vet</code>, memory-leak detection, local docs.</p>
</li>
<li><p><strong>Modern JSON</strong>: <code>encoding/json/v2</code> is the future, with huge performance gains.</p>
</li>
</ul>
<p>Go 1.25 brings meaningful improvements across performance, correctness, and developer experience. From smarter CPU usage in containers to reduced garbage collector overhead, from more predictable runtime behavior to new tools like FlightRecorder, this release shows Go’s commitment to staying simple while evolving with modern workloads. If you haven’t tried it yet, now’s the time—upgrade, experiment with the new features, and see how they can make your applications faster, safer, and easier to debug.</p>
<h2 id="heading-sources">Sources</h2>
<p><a target="_blank" href="https://go.dev/doc/go1.25">https://go.dev/doc/go1.25</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is Typecasting in Go? Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ When you’re working with data in Go, especially when you need to handle dynamic inputs like JSON from third-party APIs, understanding how to properly convert between data types is key. This helps you avoid bugs and crashes. Often times, the values re... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-typecasting-in-go/</link>
                <guid isPermaLink="false">6807a27399db81a7d80529fe</guid>
                
                    <category>
                        <![CDATA[ golang ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Golang developer ]]>
                    </category>
                
                    <category>
                        <![CDATA[ typecasting ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Pedro ]]>
                </dc:creator>
                <pubDate>Tue, 22 Apr 2025 14:06:43 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745329132242/7af1f157-973f-4375-8b09-b79a4f444805.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When you’re working with data in Go, especially when you need to handle dynamic inputs like JSON from third-party APIs, understanding how to properly convert between data types is key. This helps you avoid bugs and crashes.</p>
<p>Often times, the values returned by APIs are stored as generic <code>interface{}</code> types. These require explicit typecasting to use them correctly. But without proper type conversion, you risk data loss, unexpected behavior, or even runtime crashes.</p>
<p>In this article, we’ll explore how typecasting works in Go. You’ll learn what it is, how to do it correctly, and why it’s crucial for writing safe and reliable code.</p>
<p>You’ll learn about implicit vs explicit typecasting, common pitfalls to avoid, and how to safely work with dynamic data. We’ll also cover practical examples, including how to handle JSON data and how Go’s new generics feature can simplify type conversions.</p>
<h3 id="heading-table-of-contents">Table of Contents:</h3>
<ul>
<li><p><a class="post-section-overview" href="#heading-why-you-should-care-about-typecasting">Why You Should Care About Typecasting</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-typecasting">What Is Typecasting?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-typecast-in-go">How to Typecast in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-common-mistakes-to-avoid">Common Mistakes to Avoid</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-a-real-world-example-where-things-go-wrong">A Real-World Example: Where Things Go Wrong</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-advanced-how-to-use-generics-for-safer-typecasting">Advanced: How to Use Generics for Safer Typecasting</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-final-thoughts">Final Thoughts</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-common-type-conversion-table-in-go">Common Type Conversion Table in Go</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-helpful-packages-for-type-conversion">Helpful Packages for Type Conversion</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-references">References</a></p>
</li>
</ul>
<h2 id="heading-why-you-should-care-about-typecasting">Why You Should Care About Typecasting</h2>
<p>I decided to write about this after running into a real issue in a company's codebase. The app was pulling data from a third-party API that returned JSON objects. The values were dynamic and stored as generic <code>interface{}</code> types, but the code was trying to use them directly as <code>int</code>, <code>float64</code>, and <code>string</code> without checking or converting the types properly. This caused silent bugs, unexpected behavior, and even crashes that took hours to trace back.</p>
<p>If you're learning Go – or any language – knowing when and how to typecast can save hours of debugging. So let’s get into it.</p>
<h2 id="heading-what-is-typecasting">What Is Typecasting?</h2>
<p>Typecasting (or type conversion) is when you convert one type of variable into another. For example, turning an <code>int</code> into a <code>float</code>, or a <code>string</code> into a number. It’s a simple but essential technique for working with data that doesn’t always come in the type you expect.</p>
<p>There are two main types of typecasting:</p>
<ul>
<li><p><strong>Implicit (automatic):</strong> Happens behind the scenes, usually when it’s safe (for example, <code>int</code> to <code>float64</code> in some languages).</p>
</li>
<li><p><strong>Explicit (manual):</strong> You, the developer, are in charge of the conversion. This is the case in Go.</p>
</li>
</ul>
<p>Why does this matter? Because if you don’t convert types correctly, your program might:</p>
<ul>
<li><p>Lose data (for example, decimals getting cut off).</p>
</li>
<li><p>Crash unexpectedly.</p>
</li>
<li><p>Show incorrect results to users.</p>
</li>
</ul>
<p>I share some resources at the end of the article if you’re looking for Go packages that simplify type conversions and reduce boilerplate.</p>
<h2 id="heading-how-to-typecast-in-go">How to Typecast in Go</h2>
<p>Go is a statically typed language, and it doesn’t do implicit conversions between different types. If you want to change a type, you have to do it yourself using explicit syntax.</p>
<p>Let’s look at some basic examples:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> a <span class="hljs-keyword">int</span> = <span class="hljs-number">42</span>                     <span class="hljs-comment">// Declare a variable 'a' of type int and assign the value 42</span>
<span class="hljs-keyword">var</span> b <span class="hljs-keyword">float64</span> = <span class="hljs-keyword">float64</span>(a)        <span class="hljs-comment">// Explicitly convert 'a' from int to float64 and store it in 'b'</span>
                                  <span class="hljs-comment">// Go requires manual (explicit) type conversion between different types</span>
</code></pre>
<p>Here, we’re converting an <code>int</code> (<code>a</code>) into a <code>float64</code> (<code>b</code>). This is a widening conversion – it’s safe because every integer can be represented as a float.</p>
<p>Now the reverse:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> x <span class="hljs-keyword">float64</span> = <span class="hljs-number">9.8</span>              <span class="hljs-comment">// Declare a float64 variable 'x' with a decimal value</span>
<span class="hljs-keyword">var</span> y <span class="hljs-keyword">int</span> = <span class="hljs-keyword">int</span>(x)               <span class="hljs-comment">// Convert 'x' to an int and store it in 'y'</span>
                                 <span class="hljs-comment">// This removes (truncates) everything after the decimal point</span>
                                 <span class="hljs-comment">// So y will be 9, not 10 — it doesn't round!</span>
</code></pre>
<p>Here, we convert a <code>float64</code> to an <code>int</code>, which <strong>truncates</strong> the decimal part. This is a narrowing conversion and can lead to data loss.</p>
<p>Go forces you to be explicit so you don’t accidentally lose information or break your logic.</p>
<h2 id="heading-common-mistakes-to-avoid">Common Mistakes to Avoid</h2>
<p>When working with dynamic data like JSON or third-party APIs, it's common to use <code>interface{}</code> to represent unknown types. But you can't directly use them as specific types without checking first.</p>
<p>Here's a mistake many beginners make:</p>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> data <span class="hljs-keyword">interface</span>{} = <span class="hljs-string">"123"</span>       <span class="hljs-comment">// 'data' holds a value of type interface{} (a generic type)</span>
value := data.(<span class="hljs-keyword">string</span>)             <span class="hljs-comment">// This tries to assert that 'data' is a string</span>
                                   <span class="hljs-comment">// If it's not a string, this will panic and crash the program</span>
</code></pre>
<p>If <code>data</code> isn’t actually a <code>string</code>, this will panic at runtime.</p>
<p>A safer version would be:</p>
<pre><code class="lang-go">value, ok := data.(<span class="hljs-keyword">string</span>)         <span class="hljs-comment">// Try to convert 'data' to string, safely</span>
<span class="hljs-keyword">if</span> !ok {
    fmt.Println(<span class="hljs-string">"Type assertion failed"</span>)  <span class="hljs-comment">// If the type doesn't match, 'ok' will be false</span>
} <span class="hljs-keyword">else</span> {
    fmt.Println(<span class="hljs-string">"Value is:"</span>, value)       <span class="hljs-comment">// Only use 'value' if assertion was successful</span>
}
</code></pre>
<p>This checks the type before converting and avoids a crash. Always handle the <code>ok</code> case when asserting types from <code>interface{}</code>.</p>
<h2 id="heading-a-real-world-example-where-things-go-wrong">A Real-World Example: Where Things Go Wrong</h2>
<p>We will be using a lot of the JSON marshal and unmarshal functions. If you want to understand what these are, here’s a quick introduction or review.</p>
<h3 id="heading-what-is-marshaling-in-go">What is Marshaling in Go?</h3>
<p>Marshaling refers to the process of converting Go data structures into a JSON representation. This is especially useful when you're preparing data to be sent over the network or saved to a file. The result of marshaling is typically a byte slice containing the JSON string.</p>
<p>Unmarshaling, on the other hand, is the reverse operation. It converts JSON data into Go structures, allowing you to work with external or dynamic data formats in a strongly typed manner.</p>
<p>In typical applications, you might marshal a struct to send data via an API, or unmarshal a JSON payload received from a third-party service.</p>
<p>When using structs, marshalling and unmarshalling are straightforward and benefit from field tags that guide JSON key mapping. But when working with unstructured or unknown JSON formats, you might unmarshal into a <code>map[string]interface{}</code>. In these cases, type assertions become necessary to safely access and manipulate the data.</p>
<p>Understanding how marshalling and unmarshalling work is fundamental when building services that consume or expose APIs, interact with webhooks, or deal with configuration files in JSON format.</p>
<p>Alright, now back to our example:</p>
<p>Let’s say you get a JSON response from an API and unmarshal it into a map:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    data := []<span class="hljs-keyword">byte</span>(<span class="hljs-string">`{"price": 10.99}`</span>)        <span class="hljs-comment">// Simulated JSON input</span>

    <span class="hljs-keyword">var</span> result <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">interface</span>{}         <span class="hljs-comment">// Use a map to unmarshal the JSON</span>
    json.Unmarshal(data, &amp;result)             <span class="hljs-comment">// Unmarshal into a generic map</span>

    price := result[<span class="hljs-string">"price"</span>].(<span class="hljs-keyword">float64</span>)        <span class="hljs-comment">// Correctly assert that price is a float64</span>
    fmt.Println(<span class="hljs-string">"The price is:"</span>, price)

    total := <span class="hljs-keyword">int</span>(result[<span class="hljs-string">"price"</span>])             <span class="hljs-comment">// ❌ This will fail!</span>
}
</code></pre>
<p>This fails because <code>result["price"]</code> is of type <code>interface{}</code>. Trying to convert it directly to <code>int</code> causes a compile-time error:</p>
<blockquote>
<p>cannot convert result["price"] (map index expression of type interface{}) to type int: need type assertion</p>
</blockquote>
<p>You need to assert the type first.</p>
<h3 id="heading-the-right-way-to-do-it">The Right Way to Do It</h3>
<p>Here’s the safe and correct version:</p>
<pre><code class="lang-go"><span class="hljs-keyword">package</span> main

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

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    data := []<span class="hljs-keyword">byte</span>(<span class="hljs-string">`{"price": 10.99}`</span>)        <span class="hljs-comment">// JSON input representing a float value</span>

    <span class="hljs-keyword">var</span> result <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">interface</span>{}         <span class="hljs-comment">// Create a map to hold the parsed JSON</span>
    json.Unmarshal(data, &amp;result)             <span class="hljs-comment">// Parse the JSON into the map</span>

    <span class="hljs-comment">// Step 1: Assert that the value is a float64</span>
    priceFloat, ok := result[<span class="hljs-string">"price"</span>].(<span class="hljs-keyword">float64</span>)
    <span class="hljs-keyword">if</span> !ok {
        fmt.Println(<span class="hljs-string">"Failed to convert price to float64"</span>)
        <span class="hljs-keyword">return</span>
    }

    fmt.Println(<span class="hljs-string">"Total as float:"</span>, priceFloat)  <span class="hljs-comment">// Successfully extracted float value</span>

    <span class="hljs-comment">// Step 2: Convert the float to an int (truncates decimals)</span>
    total := <span class="hljs-keyword">int</span>(priceFloat)
    fmt.Println(<span class="hljs-string">"Total as integer:"</span>, total)     <span class="hljs-comment">// Final integer result (e.g., 10 from 10.99)</span>
}
</code></pre>
<p>This works because we first check that the value is a <code>float64</code> and only then convert it to an <code>int</code>. That two-step process – type assertion then conversion – is key to avoiding errors.</p>
<h2 id="heading-advanced-how-to-use-generics-for-safer-typecasting">Advanced: How to Use Generics for Safer Typecasting</h2>
<p>With the introduction of <strong>generics</strong> in Go 1.18, you can write reusable functions that work with any type. Generics let you define functions where the type can be specified when the function is called.</p>
<h3 id="heading-what-are-generics-in-go">What are Generics in Go?</h3>
<p>Generics were introduced in Go 1.18 to allow writing functions and data structures that work with any type. They help reduce code duplication and increase type safety by enabling parameterized types.</p>
<p>In the context of typecasting, generics allow you to write flexible helpers (like <code>getValue[T]</code>) that reduce repetitive <code>interface{}</code> assertions and make your code easier to maintain.</p>
<ul>
<li><p>Type parameters are defined with square brackets: <code>[T any]</code></p>
</li>
<li><p>The <code>any</code> keyword is an alias for <code>interface{}</code></p>
</li>
<li><p>Compile-time checks ensure the past types are used safely</p>
</li>
</ul>
<p>Generics are especially useful in libraries, APIs, and when working with dynamic structures like JSON objects.</p>
<p>Let’s say you want to extract values from <code>map[string]interface{}</code> without writing repetitive assertions:</p>
<pre><code class="lang-go"><span class="hljs-comment">// A generic function that safely retrieves and type-asserts a value from a map</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getValue</span>[<span class="hljs-title">T</span> <span class="hljs-title">any</span>]<span class="hljs-params">(data <span class="hljs-keyword">map</span>[<span class="hljs-keyword">string</span>]<span class="hljs-keyword">interface</span>{}, key <span class="hljs-keyword">string</span>)</span> <span class="hljs-params">(T, <span class="hljs-keyword">bool</span>)</span></span> {
    val, ok := data[key]                  <span class="hljs-comment">// Check if the key exists in the map</span>
    <span class="hljs-keyword">if</span> !ok {
        <span class="hljs-keyword">var</span> zero T                        <span class="hljs-comment">// Declare a zero value of type T</span>
        <span class="hljs-keyword">return</span> zero, <span class="hljs-literal">false</span>                <span class="hljs-comment">// Return zero value and false if key not found</span>
    }

    converted, ok := val.(T)              <span class="hljs-comment">// Try to convert (type assert) the value to type T</span>
    <span class="hljs-keyword">return</span> converted, ok                  <span class="hljs-comment">// Return the result and success status</span>
}
</code></pre>
<p>This function:</p>
<ul>
<li><p>Accepts any type <code>T</code> that you specify (like <code>float64</code>, <code>string</code>, and so on)</p>
</li>
<li><p>Asserts the type for you</p>
</li>
<li><p>Returns the value and a boolean indicating success</p>
</li>
</ul>
<p>Usage:</p>
<pre><code class="lang-go">price, ok := getValue[<span class="hljs-keyword">float64</span>](result, <span class="hljs-string">"price"</span>) <span class="hljs-comment">// Try to get a float64 from the map</span>
<span class="hljs-keyword">if</span> !ok {
    fmt.Println(<span class="hljs-string">"Price not found or wrong type"</span>)
}

title, ok := getValue[<span class="hljs-keyword">string</span>](result, <span class="hljs-string">"title"</span>)  <span class="hljs-comment">// Try to get a string from the map</span>
<span class="hljs-keyword">if</span> !ok {
    fmt.Println(<span class="hljs-string">"Title not found or wrong type"</span>)
}
</code></pre>
<p>This pattern keeps your code clean and readable while avoiding panics from unsafe assertions.</p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>Whether you’re just starting with Go or diving into more advanced patterns like generics, understanding typecasting is key to writing safe and reliable code.</p>
<p>It may seem like a small detail, but incorrect type conversions can cause crashes, bugs, or silent data loss – especially when working with JSON, APIs, or user input.</p>
<p>Here’s what you should take away:</p>
<ul>
<li><p>🧠 Always know the type you’re working with.</p>
</li>
<li><p>🔍 Use type assertions carefully and check the <code>ok</code> value.</p>
</li>
<li><p>🧰 Use generics to simplify repetitive assertion logic.</p>
</li>
<li><p>💡 Don’t rely on luck — be intentional with conversions.</p>
</li>
</ul>
<p>Mastering typecasting in Go will not only make you a better developer but also help you understand how typed systems work across different languages.</p>
<h2 id="heading-common-type-conversion-table-in-go">Common Type Conversion Table in Go</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td>From Type</td><td>To Type</td><td>Syntax Example</td><td>Notes</td></tr>
</thead>
<tbody>
<tr>
<td><code>int</code></td><td><code>float64</code></td><td><code>float64(myInt)</code></td><td>Safe, widening conversion</td></tr>
<tr>
<td><code>float64</code></td><td><code>int</code></td><td><code>int(myFloat)</code></td><td>Truncates decimals</td></tr>
<tr>
<td><code>string</code></td><td><code>int</code></td><td><code>strconv.Atoi(myString)</code></td><td>Returns <code>int</code> and error</td></tr>
<tr>
<td><code>int</code></td><td><code>string</code></td><td><code>strconv.Itoa(myInt)</code></td><td>Converts <code>int</code> to decimal string</td></tr>
<tr>
<td><code>[]byte</code></td><td><code>string</code></td><td><code>string(myBytes)</code></td><td>Valid UTF-8 required</td></tr>
<tr>
<td><code>string</code></td><td><code>[]byte</code></td><td><code>[]byte(myString)</code></td><td>Creates byte slice</td></tr>
</tbody>
</table>
</div><h2 id="heading-helpful-packages-for-type-conversion">Helpful Packages for Type Conversion</h2>
<ul>
<li><p><code>strconv</code>: Converting strings to numbers and vice versa</p>
</li>
<li><p><code>reflect</code>: Introspect types at runtime (use with caution)</p>
</li>
<li><p><code>encoding/json</code>: Automatic type mapping when unmarshaling</p>
</li>
<li><p><code>fmt</code>: Quick conversion to string with formatting</p>
</li>
</ul>
<h2 id="heading-references">References</h2>
<ul>
<li><p>https://go.dev/doc/effective_go</p>
</li>
<li><p>https://go.dev/doc/tutorial/generics</p>
</li>
<li><p>https://gosolve.io/golang-cast-go-type-casting-and-type-conversion/</p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Write Benchmark Tests for Your Golang Functions ]]>
                </title>
                <description>
                    <![CDATA[ Hello Gophers 👋 Let me start by asking you a question: How would you test the performance of a piece of code or a function in Go? Well, you could use benchmark tests. In this tutorial, I will show you how to use an awesome benchmarking tool that’s b... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-write-benchmark-tests-for-your-golang-functions/</link>
                <guid isPermaLink="false">66f17d16371c67381d509aea</guid>
                
                    <category>
                        <![CDATA[ golang ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Golang developer ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Testing ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Benchmark ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Pedro ]]>
                </dc:creator>
                <pubDate>Mon, 23 Sep 2024 14:37:10 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1726668982641/58540086-9f98-4ac9-8c8a-84ef45e27875.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hello Gophers 👋</p>
<p>Let me start by asking you a question: How would you test the performance of a piece of code or a function in Go? Well, you could use <strong>benchmark</strong> tests.</p>
<p>In this tutorial, I will show you how to use an awesome benchmarking tool that’s built into the Golang testing package.</p>
<p>Let’s go.</p>
<h2 id="heading-what-are-benchmark-tests">What Are Benchmark Tests?</h2>
<p>In Go, <a target="_blank" href="https://pkg.go.dev/testing#hdr-Benchmarks">benchmark tests</a> are used to measure the performance (speed and memory usage) of functions or blocks of code. These tests are part of the Go testing framework and are written in the same files as unit tests, but they are specifically for performance analysis.</p>
<h2 id="heading-example-use-case-fibonacci-sequence">Example Use Case: Fibonacci Sequence</h2>
<p>For this example, I'll be using the classic Fibonacci Sequence, which is determined by:</p>
<pre><code class="lang-plaintext">if (x &lt; 2) 
   F(0) = 1
   F(2) = 2
else 
   F(x) = F(x-1) + F(x-2)

In practice, the sequence is:
1, 1, 2, 3, 5, 8, 13, etc.
</code></pre>
<p>This sequence is important because it appears in various parts of mathematics and nature as well, as shown below:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v6fqdlmiqjob46joyfpz.png" alt="Fibonacci sequence in a spiral (like a snail shell)" width="600" height="400" loading="lazy"></p>
<p>There are several ways to implement this code, and I'll be picking two of them for our benchmark testing: the recursive and iterative methods. The main objective of the functions is to provide a <em>position</em> and return the Fibonacci number at that position.</p>
<h3 id="heading-recursive-method">Recursive Method</h3>
<pre><code class="lang-go"><span class="hljs-comment">// main.go</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">fibRecursive</span><span class="hljs-params">(n <span class="hljs-keyword">uint</span>)</span> <span class="hljs-title">uint</span></span> {
    <span class="hljs-keyword">if</span> n &lt;= <span class="hljs-number">2</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
    }
    <span class="hljs-keyword">return</span> fibRecursive(n<span class="hljs-number">-1</span>) + fibRecursive(n<span class="hljs-number">-2</span>)
}
</code></pre>
<p>The function above is a recursive implementation of calculating the Fibonacci sequence. Now I’ll break it down step by step for you as a beginner in Go.</p>
<p>Here’s your function for calculating the Fibonacci numbers:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">fibRecursive</span><span class="hljs-params">(n <span class="hljs-keyword">uint</span>)</span> <span class="hljs-title">uint</span></span> {
    <span class="hljs-keyword">if</span> n &lt;= <span class="hljs-number">2</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
    }
    <span class="hljs-keyword">return</span> fibRecursive(n<span class="hljs-number">-1</span>) + fibRecursive(n<span class="hljs-number">-2</span>)
}
</code></pre>
<h4 id="heading-1-function">1. <strong>Function:</strong></h4>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">fibRecursive</span><span class="hljs-params">(n <span class="hljs-keyword">uint</span>)</span> <span class="hljs-title">uint</span></span>
</code></pre>
<ul>
<li><p><code>func</code>: This keyword defines a function in Go.</p>
</li>
<li><p><code>fibRecursive</code>: This is the name of the function. It’s called <code>fibRecursive</code> because it calculates Fibonacci numbers using recursion.</p>
</li>
<li><p><code>n uint</code>: The function takes a single argument, <code>n</code>, which is of type <code>uint</code> (an unsigned integer). This represents the position of the Fibonacci sequence that we want to calculate.</p>
</li>
<li><p><code>uint</code>: The function returns a <code>uint</code> (unsigned integer) because Fibonacci numbers are non-negative integers.</p>
</li>
</ul>
<h4 id="heading-2-base-stage">2. <strong>Base Stage:</strong></h4>
<pre><code class="lang-go"><span class="hljs-keyword">if</span> n &lt;= <span class="hljs-number">2</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
}
</code></pre>
<ul>
<li><p>The <code>if</code> statement checks if <code>n</code> is less than or equal to 2.</p>
</li>
<li><p>In the Fibonacci sequence, the 1st and 2nd numbers are both 1. So, if <code>n</code> is 1 or 2, the function returns 1.</p>
</li>
<li><p>This is called the <strong>base stage,</strong> and it stops the recursion from going infinitely deep.</p>
</li>
</ul>
<h4 id="heading-3-recursive-stage">3. <strong>Recursive Stage:</strong></h4>
<pre><code class="lang-go"><span class="hljs-keyword">return</span> fibRecursive(n<span class="hljs-number">-1</span>) + fibRecursive(n<span class="hljs-number">-2</span>)
</code></pre>
<ul>
<li><p>If <code>n</code> is greater than 2, the function calls itself twice:</p>
<ul>
<li><p><code>fibRecursive(n-1)</code>: This will calculate the Fibonacci number for the position just before <code>n</code>.</p>
</li>
<li><p><code>fibRecursive(n-2)</code>: This will calculate the Fibonacci number for two positions before <code>n</code>.</p>
</li>
</ul>
</li>
<li><p>The function then adds these two results together, because every Fibonacci number is the sum of the two preceding numbers.</p>
</li>
</ul>
<p>For more theory on recursion, check out these <a target="_blank" href="https://www.freecodecamp.org/news/tag/recursion/">articles</a>.</p>
<h3 id="heading-iterative-method">Iterative Method</h3>
<pre><code class="lang-go"><span class="hljs-comment">// main.go</span>

<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">fibIterative</span><span class="hljs-params">(position <span class="hljs-keyword">uint</span>)</span> <span class="hljs-title">uint</span></span> {
    slc := <span class="hljs-built_in">make</span>([]<span class="hljs-keyword">uint</span>, position)
    slc[<span class="hljs-number">0</span>] = <span class="hljs-number">1</span>
    slc[<span class="hljs-number">1</span>] = <span class="hljs-number">1</span>

    <span class="hljs-keyword">if</span> position &lt;= <span class="hljs-number">2</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
    }

    <span class="hljs-keyword">var</span> result, i <span class="hljs-keyword">uint</span>
    <span class="hljs-keyword">for</span> i = <span class="hljs-number">2</span>; i &lt; position; i++ {
        result = slc[i<span class="hljs-number">-1</span>] + slc[i<span class="hljs-number">-2</span>]
        slc[i] = result
    }

    <span class="hljs-keyword">return</span> result
}
</code></pre>
<p>This code implements an <strong>iterative</strong> approach to calculate the Fibonacci sequence in Go, which is different from the <strong>recursive</strong> approach. Here’s a breakdown of how it works:</p>
<h4 id="heading-1-function-1">1. <strong>Function:</strong></h4>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">fibIterative</span><span class="hljs-params">(position <span class="hljs-keyword">uint</span>)</span> <span class="hljs-title">uint</span></span>
</code></pre>
<ul>
<li><p><code>func</code>: This keyword declares a function in Go.</p>
</li>
<li><p><code>fibIterative</code>: The name of the function suggests that it calculates Fibonacci numbers using iteration (a loop).</p>
</li>
<li><p><code>position uint</code>: The function takes one argument, <code>position</code>, which is an unsigned integer (<code>uint</code>). This represents the position of the Fibonacci sequence you want to calculate.</p>
</li>
<li><p><code>uint</code>: The function returns an unsigned integer (<code>uint</code>), which will be the Fibonacci number at the specified position.</p>
</li>
</ul>
<h4 id="heading-2-creating-a-slice-array-like-structure">2. <strong>Creating a Slice (Array-like structure):</strong></h4>
<pre><code class="lang-go">slc := <span class="hljs-built_in">make</span>([]<span class="hljs-keyword">uint</span>, position)
</code></pre>
<ul>
<li><code>slc</code> is a slice (a dynamic array in Go) that is created with the length of <code>position</code>. This slice will store Fibonacci numbers at each index.</li>
</ul>
<h4 id="heading-3-initial-values-for-fibonacci-sequence">3. <strong>Initial Values for Fibonacci Sequence:</strong></h4>
<pre><code class="lang-go">slc[<span class="hljs-number">0</span>] = <span class="hljs-number">1</span>
slc[<span class="hljs-number">1</span>] = <span class="hljs-number">1</span>
</code></pre>
<ul>
<li>The first two Fibonacci numbers are both <code>1</code>, so the first two positions in the slice (<code>slc[0]</code> and <code>slc[1]</code>) are set to <code>1</code>.</li>
</ul>
<h4 id="heading-4-early-return-for-small-positions">4. <strong>Early Return for Small Positions:</strong></h4>
<pre><code class="lang-go"><span class="hljs-keyword">if</span> position &lt;= <span class="hljs-number">2</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
}
</code></pre>
<ul>
<li>If the input <code>position</code> is <code>1</code> or <code>2</code>, the function directly returns <code>1</code>, because the first two Fibonacci numbers are always <code>1</code>.</li>
</ul>
<h4 id="heading-5-iterative-loop">5. <strong>Iterative Loop:</strong></h4>
<pre><code class="lang-go"><span class="hljs-keyword">var</span> result, i <span class="hljs-keyword">uint</span>
<span class="hljs-keyword">for</span> i = <span class="hljs-number">2</span>; i &lt; position; i++ {
    result = slc[i<span class="hljs-number">-1</span>] + slc[i<span class="hljs-number">-2</span>]
    slc[i] = result
}
</code></pre>
<ul>
<li><p>The loop starts from <code>i = 2</code> and runs until it reaches the <code>position</code>.</p>
</li>
<li><p>In each iteration, the Fibonacci number at index <code>i</code> is calculated as the sum of the two previous Fibonacci numbers (<code>slc[i-1]</code> and <code>slc[i-2]</code>).</p>
</li>
<li><p>The result is stored both in <code>result</code> and in the slice <code>slc[i]</code> for future calculations.</p>
</li>
</ul>
<h4 id="heading-6-returning-the-result">6. <strong>Returning the Result:</strong></h4>
<pre><code class="lang-go"><span class="hljs-keyword">return</span> result
</code></pre>
<ul>
<li>Once the loop finishes, the variable <code>result</code> holds the Fibonacci number at the desired position, and the function returns it.</li>
</ul>
<p>This is a more <em>efficient</em> approach to calculating Fibonacci numbers compared to recursion, especially when <code>position</code> is large, because <strong>it doesn’t repeat unnecessary calculations</strong> and we are proving by using benchmark tests<strong><em>.</em></strong> Let’s prove it.</p>
<h2 id="heading-how-to-run-the-benchmark-tests">How to Run the Benchmark Tests</h2>
<p>Now, for the benchmark tests, let’s write some test. First, you will need to create a <strong>maintest.go</strong> file. In it, using Golang's <a target="_blank" href="https://pkg.go.dev/testing@go1.22.3#hdr-Benchmarks">documentation</a> on benchmark tests, you can create the functions to be tested as follows:</p>
<pre><code class="lang-go"><span class="hljs-comment">// main_test.go</span>

<span class="hljs-comment">// Benchmark for Iterative Function</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">BenchmarkFibIterative</span><span class="hljs-params">(b *testing.B)</span></span> {
    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; b.N; i++ { 
        fibIterative(<span class="hljs-keyword">uint</span>(<span class="hljs-number">10</span>))
    }
}
<span class="hljs-comment">// Benchmark for Recursive Function</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">BenchmarkFibRecursive</span><span class="hljs-params">(b *testing.B)</span></span> {
    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; b.N; i++ {
        fibRecursive(<span class="hljs-keyword">uint</span>(<span class="hljs-number">10</span>))
    }
}
</code></pre>
<p>Let's run the test for position 10 and then increase appropriately. To run the benchmark tests, you simply run the command <code>go test -bench=NameoftheFunction</code>.</p>
<p>If you want to know more about this command, check <a target="_blank" href="https://pkg.go.dev/testing@go1.22.3#Benchmark">here</a>. Let’s check the function for <strong>position 10</strong>:</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">BenchmarkFibIterative</span><span class="hljs-params">(b *testing.B)</span></span> {
    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; b.N; i++ { 
        fibIterative(<span class="hljs-keyword">uint</span>(<span class="hljs-number">10</span>))
    }
}
</code></pre>
<pre><code class="lang-go"><span class="hljs-keyword">go</span> test -bench=BenchmarkFibIterative
Results:
cpu: Intel(R) Core(TM) i7<span class="hljs-number">-7700</span>HQ CPU @ <span class="hljs-number">2.80</span>GHz
BenchmarkFibIterative<span class="hljs-number">-8</span>         <span class="hljs-number">27715262</span>                <span class="hljs-number">42.86</span> ns/op
PASS
ok      playground      <span class="hljs-number">2.617</span>s
</code></pre>
<p>Let’s analyze with the help of this image:</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/484ap11qw8d81b43gg0v.png" alt="visit https://www.practical-go-lessons.com/chap-34-benchmarks" width="600" height="400" loading="lazy"></p>
<p>According to the image, we have 8 cores for the tests, and no time limit (it will run until completion). It took <strong>27_715_262 iterations</strong> and <strong>1.651 seconds</strong> to complete the task.</p>
<pre><code class="lang-go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">BenchmarkFibRecursive</span><span class="hljs-params">(b *testing.B)</span></span> {
    <span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i &lt; b.N; i++ {
        fibRecursive(<span class="hljs-keyword">uint</span>(<span class="hljs-number">10</span>))
    }
}
</code></pre>
<pre><code class="lang-go"><span class="hljs-keyword">go</span> test -bench=BenchmarkFibRecursive
Results:
cpu: Intel(R) Core(TM) i7<span class="hljs-number">-7700</span>HQ CPU @ <span class="hljs-number">2.80</span>GHz
BenchmarkFibRecursive<span class="hljs-number">-8</span>          <span class="hljs-number">6644950</span>               <span class="hljs-number">174.3</span> ns/op
PASS
ok      playground      <span class="hljs-number">1.819</span>s
</code></pre>
<p>Using the same image to analyze the result, in this case it took <strong>6_644_950 iterations</strong> and <strong>1.819 seconds</strong> to complete the task we have:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Fibonacci’s Function</td><td>Position</td><td>Iterations</td><td>Time to run (s)</td></tr>
</thead>
<tbody>
<tr>
<td>Iterative</td><td>10</td><td>27_715_262</td><td>1.651</td></tr>
<tr>
<td>Recursive</td><td>1<strong>0</strong></td><td>6_644_950</td><td>1.819</td></tr>
</tbody>
</table>
</div><p>The <strong>benchmark results</strong> show that the iterative approach is significantly more efficient than the recursive approach for calculating the Fibonacci sequence.</p>
<p>For position 10, the iterative function ran approximately <strong>27.7 million iterations</strong> in <strong>1.651 seconds</strong>, while the recursive function managed only <strong>6.6 million iterations</strong> in <strong>1.819 seconds</strong>. The iterative method outperformed the recursive method both in terms of iterations and time, highlighting its efficiency.</p>
<p>To proven even further this, let’s try with the <strong>position 40</strong> (4 times the previous value):</p>
<pre><code class="lang-go"><span class="hljs-comment">// Results for the Iterative Function</span>
cpu: Intel(R) Core(TM) i7<span class="hljs-number">-7700</span>HQ CPU @ <span class="hljs-number">2.80</span>GHz
BenchmarkFibIterative<span class="hljs-number">-8</span>          <span class="hljs-number">9904401</span>               <span class="hljs-number">114.5</span> ns/op
PASS
ok      playground      <span class="hljs-number">1.741</span>s

<span class="hljs-comment">// Results for the Recursive Function</span>
cpu: Intel(R) Core(TM) i7<span class="hljs-number">-7700</span>HQ CPU @ <span class="hljs-number">2.80</span>GHz
BenchmarkFibRecursive<span class="hljs-number">-8</span>                <span class="hljs-number">4</span>         <span class="hljs-number">324133575</span> ns/op
PASS
ok      playground      <span class="hljs-number">3.782</span>s
</code></pre>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Fibonacci’s Function</td><td>Position</td><td>Iterations</td><td>Time to run (s)</td></tr>
</thead>
<tbody>
<tr>
<td>Iterative</td><td>40</td><td>9_904_401</td><td>1.741</td></tr>
<tr>
<td>Recursive</td><td>40</td><td>4</td><td>3.782</td></tr>
</tbody>
</table>
</div><p>The benchmark results clearly highlight the efficiency difference between the iterative and recursive approaches for calculating Fibonacci again.</p>
<p>The <strong>iterative function</strong> completed approximately <strong>9.9 million iterations</strong> with an average execution time of <strong>114.5 nanoseconds per operation</strong>, finishing the benchmark in <strong>1.741 seconds</strong>. In stark contrast, the <strong>recursive function</strong> only completed <strong>4 iterations</strong> with an average execution time of <strong>324,133,575 nanoseconds per operation</strong> (over 324 milliseconds per call), taking <strong>3.782 seconds</strong> to finish.</p>
<p>These results demonstrate that the recursive approach is far less efficient due to repeated function calls and recalculations, making the iterative method vastly superior in both speed and resource usage, especially as input size increases.</p>
<p>Just out of curiosity, I tried <strong>position 60</strong> and it literally crashed the test:</p>
<pre><code class="lang-go"><span class="hljs-comment">// Results for the Iterative Function</span>
cpu: Intel(R) Core(TM) i7<span class="hljs-number">-7700</span>HQ CPU @ <span class="hljs-number">2.80</span>GHz
BenchmarkFibIterative<span class="hljs-number">-8</span>          <span class="hljs-number">7100899</span>               <span class="hljs-number">160.9</span> ns/op

<span class="hljs-comment">// Results for the Recursive Function</span>
SIGQUIT: quit
PC=<span class="hljs-number">0x7ff81935f08e</span> m=<span class="hljs-number">0</span> sigcode=<span class="hljs-number">0</span>

goroutine <span class="hljs-number">0</span> gp=<span class="hljs-number">0x3bf1800</span> m=<span class="hljs-number">0</span> mp=<span class="hljs-number">0x3bf26a0</span> [idle]:
runtime.pthread_cond_wait(<span class="hljs-number">0x3bf2be0</span>, <span class="hljs-number">0x3bf2ba0</span>)
...
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>If your production code is running slowly or is unpredictably slower, you can use this technique, combined with <a target="_blank" href="https://pkg.go.dev/runtime/pprof"><strong>pprof</strong></a> or other tools from the built-in testing package, to identify and test where your code is performing poorly and work on how to optimize it.</p>
<p>Remember: Code that is beautiful to the eyes is not necessarily more performant.</p>
<h3 id="heading-reference">Reference</h3>
<ul>
<li><p>Recursive &amp; Iterative functions to Fibonacci’s sequence <a target="_blank" href="https://gist.github.com/pedrobertao/a31466b3287f165f22d05f0fb2b066f2">here</a>.</p>
</li>
<li><p>Benchmark testing <a target="_blank" href="https://gist.github.com/pedrobertao/d435d9f1b0915cbc1cb54bc385f45104">here</a>.</p>
</li>
</ul>
<h3 id="heading-homework">Homework</h3>
<p>This <a target="_blank" href="https://www.meccanismocomplesso.org/en/the-fibonacci-series-three-different-algorithms-compared/">article</a> explains why for some small numbers, the recursive strategy is better. Can you find a better way to improve the recursive function? (Tip: use Dynamic Programming).</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
