DEV Community

Pavel Belokon
Pavel Belokon

Posted on

Cool ways to write functions in Go

Today, I learned something handy about Go's functions. You can actually return multiple values, unlike in JavaScript, where I would typically return an object containing the state.

  // Example
  func add(a int, b int) (int, string) {
     return a + b, "Hurray!"
  }
Enter fullscreen mode Exit fullscreen mode

You can also name the return values, which makes them local variables within the function and allows for an "empty return".

  // Example
  func add(a int, b int) (result int, message string) {
     result = a + b
     message = "Hurray!"
     return
  }
Enter fullscreen mode Exit fullscreen mode

Although I don't find using an empty return to be the best way to write functions, it’s still pretty cool.

Top comments (2)

Collapse
 
manchicken profile image
Mike Stemle

You can totally do this in JavaScript.

const add_and_multiply=(a,b) =>
  [a+b, a*b]

const [add,multiply] = add_and_multiply(20,22)
Enter fullscreen mode Exit fullscreen mode

Is Go’s approach any different under the hood that you know of?

Collapse
 
pbelokon profile image
Pavel Belokon

While they may seem similar at first glance,in Go, you directly name the return values and then retrieve them from the returned tuple, which is a distinct approach compared to destructuring in JavaScript. However, if you don't look the difference between the languages this approach is identical.