Cool ways to write functions in Go

Pavel Belokon - Aug 28 - - Dev Community

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.

. . .