Hossam Mourad

Multiple function return values in Golang

May 16, 2020

I admit it, I’m starting to fall in love with Golang. Today I learnt about a new built-in feature in Golang called “Multiple Return Values” which looks like following:

func randomCalcs(a int, b int) (int, int) {
  return a + b, a * b

add, times := randomCalcs(2, 5)

What is special about that? In other languages you have to decide what the data structure of your return value if you want to return multiple values, for example if I’m going to write the same function in TypeScript I would do it like this:

function randomCalcs(a: number, b: number): [number, number] {
  return [a + b, a * b]

const [add, times] = randomCalcs(2, 5)

The overhead thought here is that I had to decide that I need to define an array as my return type and put the values inside an array where in Golang I didn’t need to do that, I just returned multiple values.

👨‍💻 If you think there is a mistake in this post or you want to discuss, you can follow me on Twitter or send me an email. Have a nice day!

Written by Hossam Mourad.
A software developer specializing in front-end development with a passion for software development as a craftsmanship not only writing working code.
Resume / Email / LinkedIn / GitHub / Twitter