Course Content
Introduction to GoLang
Introduction to GoLang
Passing Data into the Functions
Functions are not very useful if we cannot access data from outside of them due to differences in scopes. However, we can pass data into functions using 'parameters'.
Parameters define a format for data that a function expects to receive when it is called or executed.
In the previous chapters, we examined simple functions without parameters. However, we can declare a function with parameters using the following syntax:
index
func myFunc(param1 datatype, param2 datatype, ...) { // Code }
Each parameter can have a distinct name followed by its data type. Commas separate the parameters. Parameters adhere to the same naming conventions as variables.
Here is an example that illustrates the use of functions with parameters:
index
package main import "fmt" func outThreeTimes(message string) { fmt.Println(message) fmt.Println(message) fmt.Println(message) } func sum(value1 int, value2 int) { fmt.Println("Sum:", value1 + value2) } func product(val1 int, val2 int, val3 int) { fmt.Println("Product:", val1 * val2 * val3) } func main() { outThreeTimes("Hello World") sum(17, 25) product(4, 7, 9) }
In the program above, you'll notice functions with one, two, and three parameters. It's entirely feasible to create functions with as many parameters as required.
Values can be supplied to these functions either directly or through variables. For instance, in the subsequent statement, we directly provide the string value where a parameter is anticipated:
index
outThreeTimes("Hello World")
Alternatively, we can store it within a string variable and then pass that variable into the function:
index
var msg string = "Hello World" outThreeTimes(msg)
In the statement below, you observe a blend of both approaches:
index
var a int = 4 var b int = 7 product(a, b, 9)
You can choose whichever method suits your needs best.
Note
When passing variables or data values into a function, they are referred to as arguments. In the case of
product(a, b, 9)
, the termsa
,b
, and9
are arguments. Conversely, in the function declaration,val1 int
,val2 int
, andval3 int
are known as parameters.
It's important to pass data into functions in the order defined by the parameters. For instance, in a function func myFunc(an int, b string)
, the first argument should be an integer, and the second should be a string; any other order will result in errors.
Inside the function, parameters effectively act as variables that take on the values of the passed arguments. Therefore, declaring variables with the same name as any function parameter within the function's body will lead to errors.
index
func myFunc(param int) { var param int = 1 // Error Here }
Everything was clear?