Programa Golang que utiliza múltiples valores de retorno

En Golang, podemos devolver múltiples valores a la vez desde una sola función. Se pueden lograr múltiples valores de retorno cambiando el tipo de retorno de la función en la firma de la función.

Sintaxis: 

Go

package main
 
import "fmt"
 
// declaring a function
// having return type
// of int, int
func maxmin(a int, b int) (int, int) {
 
    if a > b {
     
        // separate multiple return
        // values using comma
        return a, b
    } else {
 
        return b, a
    }
    // this function returns
    // maximum , minimum values
}
 
func main() {
 
    // declaring two values a and b
    var a = 50
    var b = 70
 
    // calling the function
    // with multiple assignments
    var max, min = maxmin(a, b)
 
    // Printing the values
    fmt.Println("Max = ", max, "\nMin = ", min)
}

Go

package main
 
import "fmt"
 
// declaring a function having
// return type of int, int
func sumDiff(a int, b int) (int, int) {
 
    return (a + b), (a - b)
 
    // this function returns sum ,
    // difference of the two numbers
}
 
func main() {
 
    // declaring two values a and b
    var a = 68
    var b = 100
 
    // calling the function
    // with multiple assignments
    var sum, diff = sumDiff(a, b)
 
    // Printing the values
    fmt.Println("Sum = ", sum, "\nDifference = ", diff)
}

Publicación traducida automáticamente

Artículo escrito por ManishKhetan y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *