A function is a block of code or a collection of statements compartmentalized together to perform a specific task. It takes an input, does some processing, and produces an output.
Every Go program has at least one function, i.e., main()
.
We can declare a function using the func
keyword.
func functionName (parameters) returnType {
// body
}
Besides the func
keyword, a function declaration contains:
functionName
: Specifies the name of the function.parameters
: Specifies the list of parameters that the function accepts. It contains the name and the type of each parameter separated by a comma. It is optional.returnType
: Specifies the type of value that function returns. It is optional.body
: Specifies what the function does.To execute a function, we need to call or invoke it.
We need to pass the required parameters along with the function name inside the main()
function. If the function returns a value, we can also store it in a variable.
The below example shows how to declare and invoke a function in Golang.
package mainimport "fmt"// declaring function "perimeter"func perimeter(num1, num2 int) int {return num1 + num2}func main() {// invoking function "perimeter"res := perimeter(20, 10)// print the res on consolefmt.Printf( "Perimeter of rectangle is : %d\n", res)}
In the above example, from line 6 to line 8, we have declared a function perimeter()
that takes two parameters, num1 and num2, and returns their sum.
Inside the main(), at line 12, we have invoked the perimeter
function and assigned the value returned by it to res
variable.
At line 15, we have output the res on the console.
A Go function can return multiple values as well. All the values that needs to be returned should be separated by a comma
.
The below example shows how to return multiple values from a function in Golang.
package mainimport "fmt"// declare function "getPerimeterAndArea"func getPerimeterAndArea(num1, num2 int) (int, int) {perimeter := num1 + num2area := num1 * num2// returning multiple valuesreturn perimeter, area}func main() {// invoke function "getPerimeterAndArea"perimeter, area := getPerimeterAndArea(20, 10)// print perimeter and area on consolefmt.Printf( "Perimeter of rectangle is : %d\n", perimeter)fmt.Printf( "Area of rectangle is : %d\n", area)}
In the above example, from line 6 to line 12, we have declared a function getPerimeterAndArea()
that takes two parameters num1 and num2, calculates the perimeter and area, and then returns both of them.
Inside the main(), at line 16, we have invoked the getPerimeterAndArea()
function and assigned the value returned by it to perimeter and area variable respectively.
At line 19 and line 20, we have output the perimeter and area on the console.