Go's Quirks
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
func () string
func () bool
type IsNil interface
func main()
It prints:
b is nil and non-nil at the same time.
Also imagine you're returning from a function:
func DoSomething(a int) IsNil
ret := DoSomething(2)
fmt.Printf("ret.IsNil(): %v\n", ret.IsNil())
fmt.Printf("ret == nil: %v\n", ret == nil)
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)
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)
func load() (data []byte, err error)
func main()
It returns:
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()
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()
but, if you change one variable, it works:
func main()
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)
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 () bool
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
func main()
Pre-1.22 Go prints:
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
println("---")
for _, f := range f
It prints:
---Capturing references into closure---
a
b
c
---
c
c
c
For goroutine:
println("---Capturing references into goroutine---")
for _, v := range a
Prints:
For deferred functions:
println("---Capturing reference into deferred function")
for _, v := range a
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
println("---")
for _, v := range d
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
time.Sleep(1 * time.Second)
println("---Capturing reference into deferred function")
for _, v := range a
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
func main()
It requires type instantiation ms := MyStruct[int], even after assigning concrete value in it.
Even making ID default still requires type declaration:
ms := MyStruct
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
but this fails:
var a int32 = MyFunc() // can infer type parameter as string
fmt.Println(a)
func MyFunc[T any]() T
Declaration requires:
var a int32 = MyFunc[int32]()
This will fail too:
func Apply(v int, f func(int) int) int
func Identity[T any](v T) T
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 (v T)
type Shape interface
type Polygon []float64 // a slice, so uncomparable
func () float64
A concrete uncomparable type is still rejected:
var s Set[Polygon] // compile error
Case 1: any
Set[any].Add([]int) // 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) // panic: hash of unhashable type main.Polygon
Case 3: error
type MyErr []string
func () string
func Contains[T comparable](s []T, target T) bool
errs := []error
Contains(errs, error(MyErr)) // panic: comparing uncomparable type main.MyErr
Case 4: an interface hidden in a struct or array
type Key struct
Set[Key].Add(Key) // panic: hash of unhashable type map[string]int
Set[[1]any].Add([1]any) // panic: hash of unhashable type func()
Case 5: comparable embedded with methods
This constraint looks stricter, but Shape still satisfies it.
type ShapeKey interface
func Index[K ShapeKey](items []K) map[K]float64
Index[Shape]([]Shape) // 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
Eq[any]([]int, 1) // false
Eq[any]([]int, []int) // 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
// Stops compiling if UserKey gains an interface field.
func _[P UserKey]()
Check at runtime when callers may pass interfaces (reflect.Value.Comparable, Go 1.20+):
func (v T) error
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 // hypothetical before 1.27
func run(x any)
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]
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 (f func(T) U) []U
Mapper[int, string].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
// What we are forced to write
type TypedClient[T any] struct
func (path string) (T, error)
users := TypedClient[User]
orders := TypedClient[Order] // 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 (f func(T) any) List[any]
s := List[int].MapAny(func(i int) any )
s[0].(string) // type safety is now checked at runtime
Workaround 4: helper type
type Pipe[T, U any] struct
func To[U, T any](l List[T]) Pipe[T, U]
func (f func(T) U) List[U]
To[string](List[int]).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]
List[int].
Map(func(i int) bool ).
Map(strconv.FormatBool)
One restriction remains: a generic method cannot implement an interface method, and interface methods cannot have type parameters.
type StringMapper interface
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 (v T) // 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)
type IntPrinter interface
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
type Square struct
func () float64
type Circle struct
func () float64
func TotalGeneric[T Shape](items []T) (sum float64)
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)
func TotalInterface(items []Shape) (sum float64)
Summing 1,000 items (Go 1.27.4, linux/amd64, range of 5 runs, roughly):
| Version | ns/op |
|---|---|
| Concrete | 548–624 |
| Generic | 2189–2473 |
| Interface | 2253–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
AreaOf(&Square) // 8 B/op, 1 allocs/op
(&Square).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...