Go Functions

Go Function is a set of statements that serve a behaviour or functionality. Functions can make the application modular.

In this tutorial, we will learn how to define a function in Go language, and how to return value(s) from a function, with examples.

Syntax

The syntax to define a Go function is

func function_name( [parameter_list] ) [return_types] {
    statement(s)
}

where

  • func is the keyword used to define a function.
  • function_name is the name by which we can call the function.
  • parameter_list is optional and these are the arguments that you provide to our function to transform them or consider them as input.
  • return_types is the list of data types of the multiple values that our function can return.

Sometimes, we may have a function that does not return any value. In that case, do not mention any return type.

ADVERTISEMENT

Function returns Single Value

In the following example, we have an add function that takes two integer values as arguments, compute their addition and return the result.

example.go

package main

import "fmt"

func add(a int, b int) int {
	var c int
	c = a+b
	return c
}

func main() {
	var n = add(3, 5)
	fmt.Printf("The sum is : %d", n)
}

Output

The sum is : 8

Function returns Multiple Values

In the following example, we have an calculate function that takes two integer values as arguments, computes their addition and multiplication, and returns these two values.

example.go

package main

import "fmt"

func calculate(a int, b int) (int, int) {
	var add int
	var mul int
	add = a+b
	mul = a*b
	return add, mul
}

func main() {
	var add, mul = calculate(3, 5)
	fmt.Printf("Addition : %d \nMultiplication : %d", add, mul)
}

Output

Addition : 8
Multiplication : 15

Function returns Nothing

In the following example, we have add function that takes two integer values for arguments, computes their addition and prints the result in the same function. The function returns no value.

example.go

package main

import "fmt"

func add(a int, b int) {
	fmt.Printf("Addition is : %d", a+b)
}

func main() {
	add(3, 5)
}

Output

Addition is : 8

We are not returning any value from the function. We are just printing the result right inside the function.

Conclusion

In this Golang Tutorial, we learned about Go Functions and how to return value(s) from a function, with the help of examples.