TIL: named return parameters in Go

Yet another piece of ✨ Go Magic ✨

I was reading through some Go code when I came upon a function that returned two things – []string and error – but the last line of the function just said return. I was confused how this worked, and since it was part of the standard library I was sure it was no bug – the code worked after all.

Turns out in Go, return parameters can be named – and they initialise their default zero-values for their type as well as define a named variables inside the function scope.

func MyFunc() (resp string, err error) {
  // this function returns "", nil

Go playground https://go.dev/play/p/yQP1oXgaYP_B

Without the named parameters an error is thrown:

func MyFunc() (string, error) {

// not enough return values
//	have ()
//	want (string, error) 

Go keeps amazing me with this stuff. There’s nice parts of the language on one side, and on the other it took until Go 1.21 (released this month!) to add a slices package with basic features like slices.Contains() – functions which needed to be implement by-hand up until now.

Additional reading





Leave a Reply