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!"
}
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
}
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)
You can totally do this in JavaScript.
Is Go’s approach any different under the hood that you know of?
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.