<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Go Puzzlers - Medium]]></title>
        <description><![CDATA[What does this Go code do? Is it what you expect? Is there now a PR you need to make? - Medium]]></description>
        <link>https://medium.com/go-puzzlers?source=rss----347a70a1f2af---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Go Puzzlers - Medium</title>
            <link>https://medium.com/go-puzzlers?source=rss----347a70a1f2af---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 02:11:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/go-puzzlers" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Go Puzzlers: Comparing Error Values]]></title>
            <link>https://medium.com/go-puzzlers/go-puzzlers-comparing-error-values-ccf26de4b594?source=rss----347a70a1f2af---4</link>
            <guid isPermaLink="false">https://medium.com/p/ccf26de4b594</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[John Montroy]]></dc:creator>
            <pubDate>Sun, 27 Nov 2022 03:08:39 GMT</pubDate>
            <atom:updated>2023-03-27T03:25:11.846Z</atom:updated>
            <content:encoded><![CDATA[<p>In Go, <a href="https://go.dev/blog/errors-are-values">errors are values</a>, as in they have a value and a type, like anything else. This is different from languages like Java or Python, where errors are exceptional things (pun intended) that require special handling and language syntax, like try / catch.</p><p>Since errors are just values in Go, we handle them by comparing them to other values. There are some subtleties here — thus, this article.</p><h3>#1 —Comparing new errors directly</h3><p>What does this code print out?</p><pre>// Go Playground: https://play.golang.com/p/f_1lmY16aKY<br>e1 := errors.New(“ohno”)<br>e2 := errors.New(“ohno”)<br>// What does this print?<br>fmt.Println(e1 == e2)</pre><p>Answer: false</p><p>We’re starting simple — all errors created via errors.New are distinct. You might know this intuitively or from reading and writing Go code, but why exactly is this true?</p><p><strong>Short answer</strong>: these errors e1 and e2 are ultimately compared as pointers. Pointers are only equal in Go if they point to the same underlying object in memory. Since each call to errors.New is a new allocation (thus the name), the pointers are not equal.</p><p><strong>It DOES NOT MATTER that the errors have the same string value “ohno” within them.</strong></p><p><strong>Long answer?</strong> Let’s take a little detour into how interfaces and comparisons work in Go. The details will aid us in subsequent puzzlers.</p><p>The code for errors.New (as of Go 1.19) is as follows:</p><pre>// New returns an error that formats as the given text.<br>// Each call to New returns a distinct error value even if the text is identical.<br>func New(text string) error {<br>  return &amp;errorString{text}<br>}<br><br>// errorString is a trivial implementation of error.<br>type errorString struct {<br>  s string<br>}<br><br>func (e *errorString) Error() string {<br>  return e.s<br>}</pre><p>A few things to note:</p><ol><li>First off, the docs on the function tell you that all values returned are distinct. Always read the docs.</li><li>For callers, errors.New returns an error interface.</li><li>The actual thing returned is of type *errorString , which implements the error interface using a pointer receiver on the Error() method.</li></ol><p>So when we call the function twice, we get two error interface values implemented by an *errorString inside them. We then compare our two error interface values. What does Go do when comparing two interface values? Let’s check the <a href="https://golang.org/ref/spec">Go Programming Specification</a>, specifically its section on <a href="https://golang.org/ref/spec#Comparison_operators">Comparison Operators</a>:</p><blockquote>Interface values are comparable. Two interface values are equal if they have <a href="https://go.dev/ref/spec#Type_identity">identical</a> dynamic types and equal dynamic values or if both have value nil.</blockquote><p>What are dynamic types and values? We once again delegate to the <a href="https://go.dev/ref/spec#Variables">spec</a>:</p><blockquote>The <em>static type</em> (or just <em>type</em>) of a variable is the type given in its declaration, the type provided in the new call or composite literal, or the type of an element of a structured variable. Variables of interface type also have a distinct <em>dynamic type</em>, which is the (non-interface) type of the value assigned to the variable at run time (unless the value is the predeclared identifier nil, which has no type).</blockquote><p>So here, for errors.New:</p><ol><li>The static type is error.</li><li>The dynamic type is *errorString.</li><li>The dynamic value is &amp;errorString{s: &quot;ohno&quot;}.</li></ol><p>So two interface values are equal if they have identical dynamic types and equal dynamic values. Well, our two errors e1 and e2 certainly have identical dynamic types: *errorString. Do they have equal dynamic values? That would mean comparing the pointer values &amp;errorString{s: &quot;ohno&quot;}. Let’s reference the spec again:</p><blockquote>Pointer values are comparable. Two pointer values are equal if they point to the same variable or if both have value nil. Pointers to distinct <a href="https://go.dev/ref/spec#Size_and_alignment_guarantees">zero-size</a> variables may or may not be equal.</blockquote><p>Well, there you have it. The dynamic values are both separately-allocated struct pointers, e.g. &amp;errorString{s: &quot;ohno&quot;}. The pointers point to different memory / different variables. So they are not equal.</p><h3>#2 — Comparing new errors by value</h3><p>Per <a href="https://go.dev/blog/go1.13-errors">the original blog post</a> introducing them:</p><blockquote>The errors.Is function compares an error to a value.</blockquote><p>So we start by comparing two errors as values using errors.Is. What does this code print out?</p><pre>// Go Playground: https://play.golang.com/p/Kl8d9MpWhc_T<br>e1 := errors.New(&quot;ohno&quot;)<br>e2 := errors.New(&quot;ohno&quot;)<br>// What does this print?<br>fmt.Println(errors.Is(e1, e2))</pre><p>Answer: false</p><p>Yes. This is good. errors.Is should not change the fact that we’re comparing two distinct variables as values. Those variables are two distinct interface values that contain two distinct pointers to structs as their dynamic values.</p><h3>#3— Comparing existing errors as values</h3><p>What does this code print out?</p><pre>// Go Playground: https://play.golang.com/p/cpimPBzUeOS<br>var (<br>  ErrCustom = errors.New(&quot;ohno&quot;)<br>)<br><br>var e1 error = ErrCustom<br>var e2 error = ErrCustom<br>// What does this print?<br>fmt.Println(e1 == e2)<br>// And this?<br>fmt.Println(errors.Is(e1, e2))</pre><p>Answer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*smUJ1wBfD_qOH1g__u6o_A.png" /></figure><p>This is good. Both variables are error interface values that contain and point to the same underlying error in memory. So this matches everything we want, and is indeed akin to how we compare error values most of the time.</p><p>Note, however — this is a bit contrived. In normal code, we’d usually compare some error returned by a function to a package-level variable. But this mimics the general idea.</p><h3>#4— Comparing custom errors as values</h3><p>Let’s try one more thing with values. What does this code print?</p><pre>// Go Playground: https://play.golang.com/p/8DGtBOuTQSp<br>type CustomError struct {<br>  Err string<br>}<br><br>func (ce CustomError) Error() string {<br>  return ce.Err<br>}<br><br>func main() {<br>  var e1 error = CustomError{Err: &quot;ohno&quot;}<br>  var e2 error = CustomError{Err: &quot;ohno&quot;}<br>  fmt.Println(errors.Is(e1, e2))<br>}</pre><p>Answer: <strong>true!</strong></p><p>Can you see what happened? We’ve created a custom error type, which implements the error interface using <strong>value receivers</strong>. That means that variables of this type actually ARE compared by value!</p><p>Recall that errors.New returns an error interface value containing an *errorString dynamic type and value. It’s returned with a *errorString because that’s how the Go library writers chose to implement error for the type — using <strong>pointer receivers</strong>. And when we compare pointers, they have to point to the same thing to be equal. This was clearly an intentional choice of semantic — errors.New should return something that is distinct / not equal to any other error, every time! Otherwise they probably would’ve called it something else.</p><p>So now we have a custom error type, which is assigned to and contained within an error interface value. But these dynamic values implement the interface with value receivers, which means they get compared not as pointers, but just as structs! And per the <a href="https://go.dev/ref/spec#Comparison_operators">Golang spec</a> again:</p><blockquote>Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-<a href="https://go.dev/ref/spec#Blank_identifier">blank</a> fields are equal.</blockquote><p>Well, the only fields here are strings, and strings are also compared directly by content:</p><blockquote>String values are comparable and ordered, lexically byte-wise.</blockquote><p>So these custom errors are equal.</p><p>What would happen if we changed our custom error to implement error using pointer receivers? Well, that would just make our situation completely identical to the original *errorString scenario, no? And we know what happens there!</p><h3>Conclusion</h3><p>We’ve looked at how to compare Go errors by value, mostly using == and errors.Is. We haven’t looked at:</p><ul><li>Comparing Go errors by type using errors.As</li><li>Comparing wrapped Go errors</li></ul><p>We’ll tackle these subjects next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccf26de4b594" width="1" height="1" alt=""><hr><p><a href="https://medium.com/go-puzzlers/go-puzzlers-comparing-error-values-ccf26de4b594">Go Puzzlers: Comparing Error Values</a> was originally published in <a href="https://medium.com/go-puzzlers">Go Puzzlers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Puzzlers: JSON Unmarshaling]]></title>
            <link>https://medium.com/go-puzzlers/go-puzzlers-json-unmarshaling-bbadfea28ee3?source=rss----347a70a1f2af---4</link>
            <guid isPermaLink="false">https://medium.com/p/bbadfea28ee3</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[John Montroy]]></dc:creator>
            <pubDate>Wed, 04 May 2022 01:21:40 GMT</pubDate>
            <atom:updated>2022-05-04T01:38:34.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*FfpDBQnvJkmHOlEy1bJQRA.png" /><figcaption>Uh-oh.</figcaption></figure><p>Go does pretty well with JSON, but there are demons lurking on the margins. Here are three edge cases that might bite you.</p><h3>#1 — JSON Tags and Casing</h3><p>What does this code print out?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb93d562d02cb13286e8e7278d2c1c66/href">https://medium.com/media/fb93d562d02cb13286e8e7278d2c1c66/href</a></iframe><p>Note what’s occuring here — the raw JSON data has fields whose casing is the OPPOSITE of the casing defined in the struct tags. Do you think this unmarshals okay?</p><p>Answer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*x-a_G84CyYpayLYf8qb6sw.png" /><figcaption>Everything unmarshals just fine!</figcaption></figure><p>Yep, everything unmarshals okay.</p><p>Golang doesn’t care about casing when unmarshaling. As long as your struct field is Exported, Go will unmarshal a raw field with any casing whatsoever. So here, for Field1, you could hand Go raw data with “field1”, “Field1”, “FIELD1”, or “fIeLd1” — Go doesn’t care, and will successfully unmarshal any of these JSON fields into the struct’s Field1.</p><h3>#2 — Default JSON Tags and Casing</h3><p>What does this code print out?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91e152faf4c8ef34a3bee8ff689c0633/href">https://medium.com/media/91e152faf4c8ef34a3bee8ff689c0633/href</a></iframe><p>Here we have the same thing, just with no explicit JSON struct tags. Is the behavior the same?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*NWbrj-rvG4TPP9RRn8RQDg.png" /><figcaption>Yes.</figcaption></figure><p>Yes. This is good. Although #1’s behavior may be surprising, it shouldn’t change based on whether you have explicit JSON tags or not.</p><h3>#3 — Duplicate JSON Fields</h3><p>What does this code print?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b28611ddfdd5c8bc96f02bd6a9ca262e/href">https://medium.com/media/b28611ddfdd5c8bc96f02bd6a9ca262e/href</a></iframe><p>Now we have many Field1 raw fields, with a mixture of different casing as well as an exact duplicate. What does Go do?</p><p>Answer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*nYnJXI-79mA1DlKpLl3gBg.png" /><figcaption>Golang takes the last-found matching occurrence.</figcaption></figure><p>It takes the last occurrence of the field, case-insensitive.</p><p>Without the raw payload, there’s no way to know that Golang has arbitrarily chosen the last occurrence of the field and dropped the others.</p><h3>Comments</h3><p>I’m far from the first person to write something up about this behavior. Here’s a <a href="https://github.com/golang/go/issues/14750">GitHub thread</a> dating back to 2016, which itself dates this issue back to Go 1.2.</p><p><a href="https://datatracker.ietf.org/doc/html/rfc7159">RFC 7159</a> defining JSON seems to be silent on this issue of case sensitivity. This means that Go’s take is just one possible take. <a href="https://mtyurt.net/post/jackson-case-insensitive-deserialization.html">Jackson seems to be case-insensitive</a> like Go, but <a href="https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-character-casing">.NET Core requires you to enable case-insensitivity</a>.</p><p>Therefore, it’s not terribly hard to get yourself in a situation where you end up with two duplicate fields with different casing in one JSON payload.</p><ul><li>Perhaps whatever API you consume emits JSON with two field names that differ only in their casing, demanding that you treat them as semantically different.</li><li>Perhaps one application emitted the field with lowercase, and another one, handling serialization differently, emitted the field with uppercase. This is already a bad place to be in, but Go doesn’t help, because it will simply choose the last occurrence without you being any wiser.</li></ul><p>So what do you do if you want case-sensitive JSON unmarshaling? Let’s tackle that in another post!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbadfea28ee3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/go-puzzlers/go-puzzlers-json-unmarshaling-bbadfea28ee3">Go Puzzlers: JSON Unmarshaling</a> was originally published in <a href="https://medium.com/go-puzzlers">Go Puzzlers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>