Parameters and Return Values

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 called a niladic function, like main.main().

Call by value or call by reference

The default way to call a function in Go is to pass a variable as an argument to a function by value. A copy is made of that variable (and the data in it). The function works with and possibly changes the copy; the original value is not changed:

Function(arg1)

If you want Function to be able to change the value of arg1 itself (in place), you have to pass the memory address of that variable with &; this is call (pass) by reference:

Function(&arg1)

Effectively, a pointer is then passed to the function. If the variable that is passed is a pointer, then the pointer is copied, not the data that it points to. However, through the pointer, the function can change the original value. Passing a pointer (a 32-bit or 64-bit value) is in almost all cases cheaper than making a copy of the object. Reference types like slices (Chapter 5), maps (Chapter 6), interfaces (Chapter 9) and channels (Chapter 12) are pass by reference by default (even though the pointer is not directly visible in the code).

Some functions just perform a task and do not return values. They perform what is called a side-effect, like printing to the console, sending a mail, logging an error, and so on. However, most functions return values, which can be named or unnamed.

The following is a program of a simple function that takes 3 parameters and returns a single value.

Get hands-on with 1400+ tech skills courses.