Functions in Go

Functions in Go

In this tutorial, we are going to discuss about functions in Go language.

Go Functions

A function, in general, is a small piece of code that is dedicated to a perform particular task based on some input values.

Every Go application has at least one function, which is main(). You can divide your code into separate functions.

Functions are used to make your code easier to understand by breaking it into small, understandable tasks that can be used more than once throughout your program.

Function allows you to extract commonly used block of code into a single component.

The input values provide extra information to a function and they are totally optional. A function’s execution may or may not return any result.

In Go language, a function is defined usingΒ funcΒ keyword.

func dosomething() {
    fmt.Println("Hello Welcome to Waytoeasylearn..!!!")
}

This function can be called from anywhere inside a function body in the program. For example, we have aΒ dosomethingΒ function that prints some characters to the standard output.

package main

import "fmt"

func dosomething() {
	fmt.Println("Hello Welcome to Waytoeasylearn..!!!")
}

func main() {
	dosomething()
}

Output

Hello Welcome to Waytoeasylearn..!!!
Function declaration

The general syntax for declaring a function in Go lang is

func functionname(parametername type) returntype {  
 //function body
}

The function declaration starts with a func keyword followed by the functionname. The parameters are specified between ( and ) followed by the returntype of the function.

The syntax for specifying a parameter is parameter name followed by the type. Any number of parameters can be specified like (parameter1 type, parameter2 type). Then there is a block of code between { and } which is the body of the function.

The parameters and return type are optional in a function. Hence the following syntax is also a valid function declaration.

func functionname() {  
 //function body
}

Lets write a function which takes the price of a single product and number of products as input parameters and calculates the total price by multiplying these two values and returns the output.

func calculateBillAmount(price int, count int) int {  
    var totalPrice = price * count
    return totalPrice
}

The above function has two input parameters price and count of type int and it returns the totalPrice which is the product of price and no. The return value is also of type int.

If consecutive parameters are of the same type, we can avoid writing the type each time and it is enough to be written once at the end. i.e., price int, count int can be written as price, count int. So The above function can hence be rewritten as,

func calculateBillAmount(price, count int) int {  
    var totalPrice = price * count
    return totalPrice
}

Now that we have a function ready, lets call it from somewhere in the code. The syntax for calling a function is functionname(parameters). The above function can be called using the code.

calculateBillAmount(50, 10)  

Following is the complete program which uses the above function and prints the total price.

package main

import (  
    "fmt"
)

func calculateBillAmount(price, count int) int {  
    var totalPrice = price * count
    return totalPrice
}
func main() {  
    price, count := 50, 10
    totalPrice := calculateBillAmount(price, count)
    fmt.Println("Total Bill amount is", totalPrice)
}

You can run above program in Go Playground

Output

Total Bill amount is 500
Multiple return values

In Go language, it is possible to return multiple values from a function.

Lets write a function rectangleProps which takes the length and width of a rectangle and returns both the area and perimeter of the rectangle.

The area of the rectangle is the product of length and width and the perimeter is twice the sum of the length and width.

package main

import (  
    "fmt"
)

func rectangleProps(length, width float64)(float64, float64) {  
    var area = length * width
    var perimeter = (length + width) * 2
    return area, perimeter
}

func main() {  
    area, perimeter := rectProps(15.8, 8.5)
    fmt.Printf("Area %f Perimeter %f", area, perimeter) 
}

Output

Area 134.300000 Perimeter 48.600000
Named return values

In Go language, it is possible to return named values from a function. If a return value is named, it can be considered as being declared as a variable in the first line of the function.

The above rectangleProps can be rewritten using named return values as

func rectangleProps(length, width float64)(area, perimeter float64) {  
    area = length * width
    perimeter = (length + width) * 2
    return // no need to explicit return value
}

In the above example, area and perimeter are the named return values in the above function.

Note that the return statement in the function does not explicitly return any value. Since area and perimeter are specified in the function declaration as return values, they are automatically returned from the function when a return statement in encountered.

Blank Identifier

_ is know as the blank identifier in Go language. It can be used in place of any value of any type. Let’s see what’s the use of this blank identifier.

The rectangleProps function returns the area and perimeter of the rectangle. What if we only need the area and want to discard the perimeter. This is where _ is of use.

The following program uses only the area returned from the rectangleProps function.

package main

import (  
    "fmt"
)

func rectangleProps(length, width float64)(float64, float64) {  
    var area = length * width
    var perimeter = (length + width) * 2
    return area, perimeter
}

func main() {  
    area, _ := rectangleProps(15.8, 8.5)
    fmt.Printf("Area %f ", area) 
}

Output

Area 134.300000
Functions in Go


Scroll to top