Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Return Values from Functions | Functions
Introduction to GoLang
course content

Contenido del Curso

Introduction to GoLang

Introduction to GoLang

1. Getting Started
2. Data Types
3. Control Structures
4. Functions
5. Arrays and Slices
6. Intro to Structs & Maps

bookReturn Values from Functions

Being able to pass data into functions is valuable, but it's equally advantageous to retrieve data from functions. This is where the return keyword becomes essential.

The return keyword allows functions to send data back to the point in the code where they were invoked. Here is the syntax for a function with a return statement:

The data_to_be_returned is where we specify an expression or a value. The returned_datatype represents the anticipated data type for the value that will be returned. This will become clearer through an example.

The subsequent program illustrates the implementation of a return statement via a function that computes and returns both the sum and product of two given integer arguments:

go

index

copy
1234567891011121314
package main import "fmt" func myFunc(value_1 int, value_2 int) int { var sum int = value_1 + value_2 var prod int = value_1 * value_2 var result int = sum + prod return result } func main() { fmt.Println(myFunc(5, 7)) }

Please note that within the Println function, we have myFunc(5, 7), and the program above produces the output 47, which results from the calculations performed by the myFunc() function. This demonstrates that the return statement conveys specific data back to the location where the function was invoked. Additionally, we can store the returned data in a variable:

go

index

copy
12
var returnedValue int = myFunc(5, 7) fmt.Println(returnedValue) // Outputs '47'

Note

A function doesn't require parameters to include a return statement.

A function cannot contain any code after a return statement, and typically, Go does not allow multiple return statements:

go

index

copy
1234567891011
// Function exits after the first return statement it encounters func exampleOne() int { return 1 return 2 // Will be ignored } // There cannot be any code after a return statement func exampleTwo() int { return 1 fmt.Println() // Error here }

Nonetheless, it's possible to employ the return statement within conditional structures to selectively return values:

go

index

copy
123456789101112131415
package main import "fmt" func myFunc() string { if(1 > 2) { return "1 is greater than 2" } else { return "2 is greater than 1" } } func main() { fmt.Println(myFunc()) }
What will be the output of the following program?

What will be the output of the following program?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 4
some-alt