DEV Community

Sukma Rizki
Sukma Rizki

Posted on

Application Of The Multiple Return Function

How to create a function that has a return value is not difficult. Just write when declaring the function all the data types of the values to be returned and in the return keyword write all the data you want to return. An example can be seen below.

package main
import "fmt"
import "math"
func calculate(d float64) (float64, float64) {
 // calculate area
 var area = math.Pi * math.Pow(d / 2, 2)
 // calculate the circumference
 var circumference = math.Pi * d
 // return the  two value
 return area, circumference
}
Enter fullscreen mode Exit fullscreen mode

The calculate() function above accepts one parameter (diameter).
used in the calculation process. In this function there are 2 things
calculated, namely the area and perimeter values. These two values are then combined
as the return value of the function.
How to define multiple return values can be seen in the code above, write it straight away
data type all return values are separated by commas, then added brackets in
among them.

func calculate(d float64) (float64, float64)
Enter fullscreen mode Exit fullscreen mode

Don't forget that in the section for writing the return keyword you must also write down all the data
which is used as the return value (with a comma).

return area, circumference

Enter fullscreen mode Exit fullscreen mode

The implementation of the calculate() function above can be seen in the following code.

func main() {
 var diameter float64 = 15
 var area, circumference = calculate(diameter)
 fmt.Printf("luas lingkaran\t\t: %.2f \n", area)
 fmt.Printf("keliling lingkaran\t: %.2f \n", circumference)
}
Enter fullscreen mode Exit fullscreen mode

Hope it is usefull
Keep Going

Top comments (0)