Golang Language Basics Tutorial: Return Values of Functions

the return value of the function

1.1 what is the return value of a function

after a function is called, the result of execution returned to the place of call is called the return value of the function.

the call needs to use a variable to receive the result

1.2 a function can return multiple values

a function can have no return value, can have a return value, or have multiple values.

package main
​
import "fmt"
​
func swap(x, y string) (string, string) {
   return y, x
}
​
func main() {
   a, b := swap("Mahesh", "Kumar")
   fmt.Println(a, b)
}
func SumAndProduct(A, B int) (add int, Multiplied int) {
add = A+B
Multiplied = A*B
return
}

1.3 blank identifiers

_ is a blank identifier in Go. It can replace any value of any type. Let’s look at the usage of this blank identifier.

For example, the result of the rectProps function is the area and perimeter, if we only want the area, not the perimeter, we can use a blank identifier.

sample code:

package main
​
import (  
    "fmt"
)
​
func rectProps(length, width float64) (float64, float64) {  
    var area = length * width
    var perimeter = (length + width) * 2
    return area, perimeter
}
func main() {  
    area, _ := rectProps(10.8, 5.6) // perimeter is discarded
    fmt.Printf("Area %f ", area)
}

Leave a Reply