Course Content
Introduction to GoLang
Introduction to GoLang
Return 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:
index
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:
index
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:
index
// 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:
index
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()) }
Thanks for your feedback!