...

/

Parameters and Return Values

Parameters and Return Values

This lesson will discuss the elements of functions like parameters and return values in detail.

Introduction

A function can take parameters to use in its code, and it can return zero or more values (when more values are returned, one of the values often speaks of a tuple of values). This is also a great improvement compared to C, C++, Java, and C#, and it is particularly handy when testing whether or not a function execution has resulted in an error (as we studied in Chapter 3).

Parameters of a function

Parameters can be actual parameters or formal parameters. The key difference between them is that actual parameters are the values that are passed to the function when it is invoked, while formal parameters are the variables defined by the function that receives values when the function is called. Remember the greeting function from the previous lesson. We called it using the following statement:

greeting(lastName)

And we implemented the function as:

func greeting(name string) {
    println("In greeting: Hi!!!!!", name)
    name = "Johnny"
    println("In greeting: Hi!!!!!", name)
}

Here, lastName is the actual parameter, and name is the formal parameter.

Return from a function

Returning value(s) is done with the keyword return. In fact, every function that returns at least 1 value must end with return or panic (see Chapter 11). The code after return in the same block is not executed anymore. If return is used, then every code-path in the function must end with a return statement.

Note: A function with no parameters is ...