https://mfirhas.com/rss.xml

Go's Quirks

04 Dec 2026

Every programming language has its quirks, and Go is no exception.

Some are intentional design choices, some are consequences of the language specification, and others are simply behaviors that aren't immediately obvious.

This is a collection of Go quirks worth knowing, exploring, and occasionally questioning from my own experience writing Go.

1. Schrödinger's Interface

An interface that is nil and non-nil at the same time.

This is one of the most confusing behavior in Go code. Imagine you have logic relying on nil-ness of an interface, this could cause hidden bug.

package main

import "fmt"

type MyError struct{ msg string }

func (e *MyError) Error() string {
	if e != nil {
		return e.msg
	}
	return "<no_error>"
}

func (e *MyError) IsNil() bool {
	return e == nil
}

type IsNil interface {
	IsNil() bool
}

func main() {
	var a IsNil
	fmt.Printf("a = %v\n", a)
	fmt.Printf("a == nil: %v\n", a == nil)

	fmt.Println("-----------------")

	var ptr *MyError
	var b IsNil = ptr
	fmt.Printf("b = %v\n", b)
	fmt.Printf("b.IsNil(): %v\n", b.IsNil())
	fmt.Printf("b == nil: %v\n", b == nil)

	fmt.Println("-----------------")

	ptr = &MyError{msg: "my error"}
	var c IsNil = ptr
	fmt.Printf("c = %v\n", c)
	fmt.Printf("c.IsNil(): %v\n", c.IsNil())
	fmt.Printf("c == nil: %v\n", c == nil)

}

It prints:

a = <nil>
a == nil: true
-----------------
b = <no_data>
b.IsNil(): true
b == nil: false
-----------------
c = my error
c.IsNil(): false
c == nil: false

b is nil and non-nil at the same time.

Also imagine you're returning from a function:

func DoSomething(a int) IsNil {
	var val *MyType
	if a < 0 {
		val = &MyType{msg: "a message"}
		return val
	}
	return val
}

ret := DoSomething(2)
fmt.Printf("ret.IsNil(): %v\n", ret.IsNil())
fmt.Printf("ret == nil: %v\n", ret == nil)
ret.IsNil(): true
ret == nil: false

The function return non-nil interface no matter which path your logic goes. This is more prevalent for error interface, where nil-ness affects the logic.

This happen because an interface in Go is a fat pointer. This fat pointer contains 2 data segments: 1 containing the concrete data, and other 1 containing vtable of data type and its methods. When you fill the interface with nil pointer var ptr *MyType, you're initializing the interface with nil value with vtable containing the type and methods. This is technically not nil, even though the data segment is nil.

One way to solve this is to assign nil directly to the interface.

2. Naked Return

Non-deterministic return values

Consider this:

func process(input Input) (output Output, err error) {
	// ... logics
	return
}

It's hard to see the values being returned, few changes might affect the return values completely. If you forget setting the values, it returns emptied. Not forgetting the presence of defer. Too much fuss here.

Worst thing might happen is shadowing:

package main

import (
	"errors"
	"fmt"
)

func read() ([]byte, error) {
	return nil, errors.New("disk failure")
}

func load() (data []byte, err error) {
	if true {
		data, err := read()
		if err != nil {
			fmt.Println("inner err:", err)
		}
		_ = data
	}
	return
}

func main() {
	data, err := load()
	fmt.Printf("data=%v err=%v\n", data, err)
}

It returns:

inner err: disk failure
data=[] err=<nil>

Both data and err got shadowed by inner scope assigning to new variables with the same names.

The best practice is to avoid naked return and return the variables directly.

3. Variables Shadowing

You can't declare multiple variables with the same names.

func main() {
	err := operation()

	// rest of the code...

	err := operation_2()
}

You're forced to change variable name for second err, because you already declared one on top.

Also in multiple return values, this fails:

func main() {
	result, err := operation()
	// ...
	result, err := operation()
}

but, if you change one variable, it works:

func main() {
	result, err := operation()
	// ...
	res, err := operation()

	// or...

	res, errr := operation()
	// ...
	res, err := operation()
}

The change in one of variables, invalidate the shadowing.

...and here it comes the weirdest of all:

This works:

err := operation()
// ...
res, err := operation2()
// ...
ress, err := operation2()

This also works:

err := operation()
// ...
res, err := operation2()
// ...
res, errr := operation2()

This works too:

err := operation()
// ...
ress, err := operation2()
// ...
res, err := operation2()

BUT this doesn't:

err := operation()
// ...
res, errr := operation2()
// ...
res, err := operation2() // no new variables on left side of :=

Now it works again:

err := operation()
// ...
ress, errr := operation2()
// ...
res, err := operation2()

See the inconsistency?!, it's weird.

So, you end up renaming every variables, or you can declare variables on top, and mutate them at any lines.

4. Multiple returns and no tuple

Instead of tuple, we have multiple returns

Golang has no true tuple type. Instead, we have multiple returns and it's not a type, just syntactic. There's no type to hold these multiple values.

Everytime we invoke function returning multiple values, we have to unpack them:

ret, err := Function()

The weird thing is, we can pack multiple return values into function's parameter variable if it matches:

Operation(Function())


func Function() (string, error) {
	// ...
}

func Operation(ret string, err error) {
	// ...
}

Another inconsistency in Go.

Lacks of tuple make us unable to chain multiple functions. We have to unpack it at return site, then continue on another function.

5. No Enum

No enums, just constants, multipel returns, iota, and a little discipline.

This is the most interesting thing about Go, it has no enum, or sum type, or discriminated union. We cannot represent a type of values with multiple possibilities. One of place where it's frequently used is returning from fallible operation, where the result might be success or fail. Instead of returning either one, Go does return both success and failed value. This relies on the error type, if it's not nil, then the success value is rubbish and must be ignored. We have to mind quirk no.1, since error is interface.

Another way for handling enum is using constants and iota.

type Enum string

const (
	ENUM_A Enum = "enum_a"
	ENUM_B Enum = "enum_b"
)
// ...
var a Enum
a := ENUM_A
b := ENUM_B
// ...
a = "sdfsdf" // assign arbitrary string value into enum constants

What's the point of having Enum type, if we can assign arbitrary value into it? It ends up just like typical constants.

But, if we declare the type or initiate a value first, then assigning it to Enum won't work.

So there's this distinction between untyped constant and variables. We can assign untyped constants to named constants(like Enum), but we can't assign variable.

For example, this won't work:

type Enum string

const (
	ENUM_A Enum = "enum_a"
	ENUM_B Enum = "enum_b"
)

a := ENUM_A
b := ENUM_B

var c string
a = c // cannot assign var c with type `string` to `Enum`
c = a // cannot assign const a with type `Enum` to string var
c = ENUM_A // same issue

You have to wrap it with enum type to make it works:

a = Enum(c) // wrap `string` type into `Enum` type.

Interestingly, this works for arbitrary values we wrap inside Enum enum type.

a = Enum("non-existent value")
var b string
a = Enum(b)

Both Enum("non-existent value") and b are not in range of enums we declared(ENUM_A, ENUM_B).

Again, those enums declaration end up just like normal constants declaration.

Using iota makes no difference:

type Status int

const (
	A = iota
	B
	C
)

func Process(status Status) {
	if status == C {
		// ...
	}
	// ...
}

Process(10) // this works

var e int64
Process(Status(e)) // this works, because we wrap it inside enum type

f := 123
Process(f) // this failed

This makes using enum this way is pointless, since you can put arbitrary values losing the purpose of the enum/sum type.

You can add method for the enum type to validate the enum type, but this has 2 problems:

  • This checks at runtime, not compile-time, and people might forget invoking the validation method.
  • You can't validate it exhaustively, you always need to make sure when you add new variants you update the validation method.
func (e Enum) Valid() bool {
	switch e {
	case ENUM_A, ENUM_B:
		return true
	default:
		return false
	}
}

This becomes problem when you forget to update the method when changing the Enum value.

6. Loop's variable references

Fixed since Go v1.22

This is the most notorious issue in Go. It happens when you take reference to loop's variable, you won't get what you expect. This happen to Go before version 1.22.

package main

import (
	"fmt"
)

type User struct {
	Name string
}

func main() {
	println("---Storing same references pointing to last item after iterations finished---")
	users := []User{{"dono"}, {"kasino"}, {"indro"}}
	byName := map[string]*User{}

	for _, u := range users {
		byName[u.Name] = &u // taking reference for u
	}

	fmt.Println(byName["dono"].Name)
	fmt.Println(byName["kasino"].Name)
	fmt.Println(byName["indro"].Name)

	println("---Print the variable inside the loop directly---")

	a := []string{"a", "b", "c"}
	for _, v := range a {
		fmt.Println(v)
	}

	println("---Reference loop var, but print directly inside the loop---")

	var b *string
	for _, v := range a {
		b = &v
		fmt.Println(*b)
	}

	println("---Taking the value directly instead of reference---")

	var c []string
	for _, v := range a {
		c = append(c, v)
	}
	fmt.Println(c)

	println("---Taking the references and print them after loop finished---")

	var d []*string
	for i, v := range a {
		d = append(d, &v)
		fmt.Println(*d[i])
	}
	println("---")
	for _, v := range d {
		fmt.Println(*v)
	}

}

Pre-1.22 Go prints:

---Storing same references pointing to last item after iterations finished---
indro
indro
indro
---Print the variable inside the loop directly---
a
b
c
---Reference loop var, but print directly inside the loop---
a
b
c
---Taking the value directly instead of reference---
[a b c]
---Taking the references and print them after loop finished---
a
b
c
---
c
c
c

You can see the ones causing problem is when we reference the loop var, and read it later.

Especially the last one, if we print the reference inside the loop, it's still pointing to correct value, past it, we get the last items in the iterations.

This happens because all of the loop iterations share 1 variable, and anything that held on to the variable past its iteration saw whatever was written there later.

This also happens for closure, goroutines and deferred function, when we refer the variable inside them, we capture it by reference.

println("---Capturing references into closure---")
var f []func() string
for i, v := range a {
	f = append(f, func() string { return v })
	fmt.Println(f[i]())
}
println("---")
for _, f := range f {
	fmt.Println(f())
}

It prints:

---Capturing references into closure---
a
b
c
---
c
c
c

For goroutine:

println("---Capturing references into goroutine---")
for _, v := range a {
	go func() {
		fmt.Println(v)
	}()
}

Prints:

---Capturing references into goroutine---
c
c
c

For deferred functions:

println("---Capturing reference into deferred function")
for _, v := range a {
	defer func() {
		fmt.Println(v) // runs when main returns
	}()
}

Prints:

---Capturing reference into deferred function
c
c
c

Before v1.22, this issue is fixed by creating a variable inside the loop storing the loop's variable, so each iteration store different values. For closures, goroutine and deferred function, the fix is to pass the loop's variable into closure's/goroutine's parameter.

println("---Taking the references and print them after loop finished---")

var d []*string
for i, v := range a {
	v := v
	d = append(d, &v)
	fmt.Println(*d[i])
}
println("---")
for _, v := range d {
	fmt.Println(*v)
}

It now prints:

---Taking the references and print them after loop finished---
a
b
c
---
a
b
c

Or:

println("---Capturing references into goroutine---")
for _, v := range a {
	go func(v string) {
		fmt.Println(v) // now it refers to captured value of v
	}(v)
}
time.Sleep(1 * time.Second)
println("---Capturing reference into deferred function")
for _, v := range a {
	defer func(v string) {
		fmt.Println(v) // now it refers to captured value of v
	}(v)
}

It prints:

---Capturing references into goroutine---
a
c
b
---Capturing reference into deferred function
c
b
a

Worth remembering that this issue caused notorious bug in Let's Encrypt.

All of these issues are already fixed since 1.22, and each iteration will bring its own variable.

This fix cause 2 problem:

  • It's backward incompatible, so make sure the update won't affect existing behavior.
  • It's introducing possible heap allocation for the variable each iteration, this is the price of correct behavior.

7. No Generics

Added since Go v1.18

This is one of the most controversial about Go, it has no generics or type parameter. You end up with duplicate code for different types, or utilizing interface dealing with type unsafetiness.

func OperationInt32(in int32) error {
	// ...
}

func OperationInt32(in int64) error {
	// ...
}

func OperationString(in string) error {
	// ...
}
...

People can avoid this by using interface, but it incurs additional overhead for pointer/heap-alloc and reflection.

After being added in 1.18, there are still several issues with it, they are:

7.1 Weak Type Inference

This won't work:

type MyStruct[T any] struct {
	ID   T
	Name string
}

func main() {
	ms := MyStruct{ // requires type parameter declaration here
		Name: "test",
		ID:   123,
	}
	fmt.Println(ms)
}

It requires type instantiation ms := MyStruct[int], even after assigning concrete value in it.

Even making ID default still requires type declaration:

ms := MyStruct{ // requires type parameter declaration here
	Name: "test",
}

But the inference works for generic function:

a := MyFunc("asd") // can infer type parameter as string
fmt.Println(a)

func MyFunc[T any](t T) T {
	return t
}

but this fails:

var a int32 = MyFunc() // can infer type parameter as string
fmt.Println(a)

func MyFunc[T any]() T {
	var t T
	return t
}

Declaration requires:

var a int32 = MyFunc[int32]()

This will fail too:

func Apply(v int, f func(int) int) int { return f(v) }
func Identity[T any](v T) T            { return v }

Apply(1, Identity) // [int] is required

This issue is fixed throughout several versions: 1.20, 1.21 and 1.27.

7.2 Interface slicing in generic constraint

Before 1.20, an interface type such as any or error did not satisfy comparable, even though == worked on it in ordinary code. Go 1.20 allowed it. The catch is that the compiler only sees the interface, not the value inside. If that value is uncomparable, such as a slice, map or func, the code compiles and may panic at runtime.

The examples below share these declarations:

type Set[T comparable] map[T]struct{}

func (s Set[T]) Add(v T) { s[v] = struct{}{} }

type Shape interface{ Area() float64 }

type Polygon []float64 // a slice, so uncomparable

func (p Polygon) Area() float64 { return 0 }

A concrete uncomparable type is still rejected:

var s Set[Polygon] // compile error

Case 1: any

Set[any]{}.Add([]int{1}) // panic: hash of unhashable type []int

Case 2: a non-empty interface

Methods on an interface say nothing about whether its implementations are comparable.

Set[Shape]{}.Add(Polygon{1}) // panic: hash of unhashable type main.Polygon

Case 3: error

type MyErr []string

func (e MyErr) Error() string { return "my error" }

func Contains[T comparable](s []T, target T) bool {
	for _, v := range s {
		if v == target {
			return true
		}
	}
	return false
}

errs := []error{MyErr{"a"}}
Contains(errs, error(MyErr{"a"})) // panic: comparing uncomparable type main.MyErr

Case 4: an interface hidden in a struct or array

type Key struct {
	ID    int
	Extra any
}

Set[Key]{}.Add(Key{1, map[string]int{}}) // panic: hash of unhashable type map[string]int

Set[[1]any]{}.Add([1]any{func() {}}) // panic: hash of unhashable type func()

Case 5: comparable embedded with methods

This constraint looks stricter, but Shape still satisfies it.

type ShapeKey interface {
	comparable
	Shape
}

func Index[K ShapeKey](items []K) map[K]float64 {
	m := map[K]float64{}
	for _, it := range items {
		m[it] = it.Area()
	}
	return m
}

Index[Shape]([]Shape{Polygon{1}}) // panic: hash of unhashable type main.Polygon

Case 6: it doesn't always panic

== panics only when both sides hold the same uncomparable type. This can let the bug slip through tests.

func Eq[T comparable](a, b T) bool { return a == b }

Eq[any]([]int{1}, 1)        // false
Eq[any]([]int{1}, []int{1}) // panic: comparing uncomparable type []int

Map keys are different: hashing an uncomparable value panics even on a lookup.

_, ok := Set[any]{}[[]int{}] // panic: hash of unhashable type []int

How to defend

Use a concrete key type where you can. Set[string] cannot hit this problem.

Assert strict comparability for types you own:

func isComparable[T comparable]() {}

type UserKey struct{ ID int }

// Stops compiling if UserKey gains an interface field.
func _[P UserKey]() { _ = isComparable[P] }

Check at runtime when callers may pass interfaces (reflect.Value.Comparable, Go 1.20+):

func (s Set[T]) TryAdd(v T) error {
	if !reflect.ValueOf(&v).Elem().Comparable() {
		return fmt.Errorf("unhashable value of type %T", v)
	}
	s[v] = struct{}{}
	return nil
}

Takeaway: since Go 1.20, comparable means "== compiles", not "== never panics".

7.3 No Generic Method

This is one of the most notorious issues with Go generics at release: before Go 1.27, there was no way to declare a method with its own type parameters.

type List[T any] []T

// Go 1.26 and earlier: syntax error: method must have no type parameters
func (l List[T]) Map[U any](f func(T) U) List[U] { /* ... */ }

A method could only use the type parameters of its receiver.

Why it was left out

Interfaces in Go are satisfied implicitly and can be checked at runtime. Consider:

type Doubler struct{}

func (Doubler) Apply[T int | float64](v T) T { return v * 2 } // hypothetical before 1.27

func run(x any) {
	if a, ok := x.(interface{ Apply(int) int }); ok {
		a.Apply(1) // needs Apply[int], which may never be instantiated elsewhere
	}
}

If generic methods could satisfy interfaces, the compiler would have to know every instantiation in advance, or generate code at runtime, or use a slower shared implementation.

Workaround 1: top-level function

func Map[T, U any](l List[T], f func(T) U) List[U] {
	out := make(List[U], len(l))
	for i, v := range l {
		out[i] = f(v)
	}
	return out
}

This is the idiomatic choice, but chained calls read inside out:

Reduce(Map(Filter(l, isEven), square), 0, add)

Workaround 2: move the parameter to the type

type Mapper[T, U any] []T

func (m Mapper[T, U]) Map(f func(T) U) []U { return Map(List[T](m), f) }

Mapper[int, string]{1, 2}.Map(strconv.Itoa)

U is now fixed when the value is created, even if Map is the only method that needs it.

But this creates another problem: what if the type doesn't need a type parameter at all? We add one just for the sake of a generic method.

// What we want: Client itself is not generic
type Client struct{ baseURL string }

// What we are forced to write
type TypedClient[T any] struct{ baseURL string }

func (c TypedClient[T]) Get(path string) (T, error) {
	var out T
	// fetch c.baseURL+path and decode into out
	return out, nil
}

users := TypedClient[User]{baseURL: url}
orders := TypedClient[Order]{baseURL: url} // another value just to change T

T describes only what Get returns, yet it becomes part of the client's type. TypedClient[User] and TypedClient[Order] are different types, so one can't be used where the other is expected.

Workaround 3: return any

func (l List[T]) MapAny(f func(T) any) List[any] { return Map(l, f) }

s := List[int]{1, 2}.MapAny(func(i int) any { return strconv.Itoa(i) })
s[0].(string) // type safety is now checked at runtime

Workaround 4: helper type

type Pipe[T, U any] struct{ l List[T] }

func To[U, T any](l List[T]) Pipe[T, U]      { return Pipe[T, U]{l} }
func (p Pipe[T, U]) Map(f func(T) U) List[U] { return Map(p.l, f) }

To[string](List[int]{1, 2}).Map(strconv.Itoa)

This keeps type safety, but adds ceremony for every output type.

Go 1.27

Generic methods are now allowed, so calls chain from left to right:

func (l List[T]) Map[U any](f func(T) U) List[U] { return Map(l, f) }

List[int]{1, 2}.
	Map(func(i int) bool { return i > 1 }).
	Map(strconv.FormatBool)

One restriction remains: a generic method cannot implement an interface method, and interface methods cannot have type parameters.

type StringMapper interface {
	Map(func(int) string) List[string]
}

var _ StringMapper = List[int]{} // compile error: wrong type for method Map

7.4 Generic Method can't implement interface

After generic method support in 1.27, it can't satisfy interface.

This still works:

type Printer[T any] struct{}

func (Printer[T]) Print(v T) { fmt.Println(v) } // not a generic method

var _ IntPrinter = Printer[int]{} // OK

But this doesn't:

type Printer struct{}

// Generic method, OK since 1.27
func (Printer) Print[T any](v T) { fmt.Println(v) }

type IntPrinter interface {
	Print(v int)
}

var _ IntPrinter = Printer{} // error: wrong type for method Print

7.5 Pointer Type Overhead

You might expect Go to generate a separate copy of a generic function for each type, as Rust does. Instead, the gc compiler shares code between types with the same GC shape: roughly, types with the same underlying type. All pointer types share one shape.

type Shape interface{ Area() float64 }

type Square struct{ side float64 }

func (s *Square) Area() float64 { return s.side * s.side }

type Circle struct{ r float64 }

func (c *Circle) Area() float64 { return 3.14 * c.r * c.r }

func TotalGeneric[T Shape](items []T) (sum float64) {
	for _, it := range items {
		sum += it.Area()
	}
	return
}

TotalGeneric[*Square] and TotalGeneric[*Circle] both run the same body, TotalGeneric[go.shape.*uint8]. That body doesn't know which Area to call, so it receives a hidden dictionary and calls through it. The call is indirect, and here Area isn't inlined.

Measuring it

Compare it with a concrete function and a plain interface:

func TotalConcrete(items []*Square) (sum float64) {
	for _, it := range items {
		sum += it.Area()
	}
	return
}

func TotalInterface(items []Shape) (sum float64) {
	for _, it := range items {
		sum += it.Area()
	}
	return
}

Summing 1,000 items (Go 1.27.4, linux/amd64, range of 5 runs, roughly):

Versionns/op
Concrete548–624
Generic2189–2473
Interface2253–2523

The generic version is about 4x slower than the concrete one, and no faster than the interface. Area is tiny, so this is close to a worst case. When a method does real work, the call overhead matters much less.

It can also cause heap allocation

Because the compiler can't see which method is called, it may have to assume the pointer escapes.

func AreaOf[T Shape](s T) float64 { return s.Area() }

AreaOf(&Square{2})  // 8 B/op, 1 allocs/op
(&Square{2}).Area() // 0 B/op, 0 allocs/op

What to do

  • Benchmark first. Most code won't notice.
  • Write concrete functions for hot paths, at the cost of some duplication.
  • Pass a slice of values where the logic doesn't need methods through a type parameter.
  • Inspect the compiler's decisions with go build -gcflags=-m=2.

Switching to a pointer constraint such as interface{ *E; Shape } does not remove the overhead. It was just as slow in the same benchmark.

These results depend on the compiler version, so measure with the one you use.


These are only few of several quirks I ever faced. More to comes on next part...