Function

Parameters of Function

A function can take zero or more arguments. In this example, add takes two parameters of type int. Notice that the type comes after the variable name.

package main

import "fmt"

func add(x int, y int) int {
	return x + y
}

func main() {
	fmt.Println(add(42, 13))
}

When two or more consecutive named function parameters share a type, you can omit the type from all but the last. In this example, we shortened

x int, y int

to

x, y int

Here is an example:

package main

import "fmt"

func add(x, y int) int {
	return x + y
}

func main() {
	fmt.Println(add(42, 13))
}

Returning Multiple Values

A function can return any number of results. Seperate the values with a comma. In the following example, the swap function returns two values:

package main

import "fmt"

func swap(x, y string) (string, string) {
	return y, x
}

func main() {
	a, b := swap("hello", "world")
	fmt.Println(a, b)
}

Specifying Return Type

To specify the return type use the type just before the function body:

func add(x int, y int) int {
	return x + y
}

Here before the second bracket of the function body we have int, means the function will return a value which is integer type.

To return multiple values seperate the type with a comma and enclose them within parenthesis.

func swap(x, y string) (string, string) {
	return y, x
}

In the above function the return type is (string, string), means the function will return two values and their types are string.

Named Return

Go's return values may be named. If so, they are treated as variables defined at the top of the function. These names should be used to document the meaning of the return values.

A return statement without arguments returns the named return values. This is known as a "naked" return. Naked return statements should be used only in short functions, as with the example shown here. They can harm readability in longer functions.

package main

import "fmt"

func split(sum int) (x, y int) {
	x = sum * 4 / 9
	y = sum - x
	return
}

func main() {
	fmt.Println(split(17))
}

In the above example, we have a function split and it has a named return type:

(x, y int)

As we are mentioning the name of the variable along with the return type, it is called named return. Now if you use return statement without any arguments, these named variables will be returned. The output of the above program will be:

7 10