Golang Beginner Tutorial Series – Functions Multiple Return Values

The Golang function has multiple return values

Go allows a function to have multiple return values, which are defined in the following structure:

func SumProdDiff(i, j int) (int, int, int)

since there are multiple return values, they need to be enclosed in. inside the above function, when returned, the following statement should be written:()return

return sum, prod, diff

when called, by assigning an operator

s, p, d := SumProdDiff(value1, value2)

if the number and definition of the returned values in the statement differ, a compilation error is generated.returnnot enough arguments to return error.

when the function is defined, it is also possible to declare the name of the return value, which is described later in this section, and its definition structure resembles the following:

func SumProdDiff(i, j int) (s int, p int, d int)

multiple return values

in the following code, you define a function that returns the sum, product, and difference of two numbers at the same time.

package main

import (
    "fmt"
)

func SumProductDiff(i, j int) (int, int, int) {
    return i+j, i*j, i-j
}

func main() {
    sum, prod, diff := SumProductDiff(3,4)
    fmt.Println("Sum:", sum, "| Product:",prod, "| Diff:", diff)
}
Sum: 7 | Product: 12 | Diff: -1

handle errors with multiple return values

multiple return values allow you to effectively handle the occurrence of errors. typical processing is as follows:

retValue, err := my_function()
    if err == nil { //go ahead with normal code
    } else { //error handling code
    }

in the following code, implement a function that takes the square root. when a negative number is encountered, an error is returned directly. the function is called to check for errors before the function is executed. the following code is poorly written and is mainly used to illustrate the use.

package main

import (
    "fmt"
    "errors"
    "math"
)

func MySqrt(f float64) (float64, error) {
    //return an error as second parameter if invalid input
    if (f < 0) {
        return float64(math.NaN()), errors.New("I won't be able to do a sqrt of negative number!")
    }

    //otherwise use default square root function
    return math.Sqrt(f), nil
}

func main() {
    fmt.Print("First example with -1: ")
    ret1, err1 := MySqrt(-1)
    if err1 != nil {
        fmt.Println("Error! Return values are", ret1, err1)
    } else {
        fmt.Println("It's ok! Return values are", ret1, err1)
    }

    fmt.Print("Second example with 5: ")
    //you could also write it like this
    if ret2, err2 := MySqrt(5); err2 != nil {
        fmt.Println("Error! Return values are", ret2, err2)
    } else {
        fmt.Println("It's ok! Return values are", ret2, err2)    }
}
First example with -1: Error! Return values are NaN I won't be able to do a sqrt of negative number!
Second example with 5: It's ok! Return values are 2.23606797749979

return value naming

Go allows the return value to be named when defining a function, and of course these variables can be used in the function. in the statement, these values are returned automatically without displaying these values. of course, the statement must still be written, otherwise the compiler will report an error.returnGoreturn

a return value variable defined in a function is automatically assigned to . that is, the variables are automatically initialized – the type is initialized to , initialized to , and the struct is initialized according to its components.zero-valueint0string""

package main

import (
    "fmt"
    "errors"
    "math"
)

//name the return variables - by default it will have 'zero-ed' values i.e. numbers are 0, string is empty, etc.
func MySqrt2(f float64) (ret float64, err error) {
    if (f < 0) {
        //then you can use those variables in code
        ret = float64(math.NaN())
        err = errors.New("I won't be able to do a sqrt of negative number!")
    } else {
        ret = math.Sqrt(f)
        //err is not assigned, so it gets default value nil
    }
    //automatically return the named return variables ret and err
    return
}

func main() {
    fmt.Println(MySqrt2(5))
}
2.23606797749979 <nil>

note that the change return value can be displayed. in the above code, if written, the named variable will be ignored and the true value returned is return 5, nil5, nil


Golang is a magical language that lets us progress together

Leave a Reply