Passing Arrays to Functions in Go
If you want to pass an array as a parameter to a function, you need to declare the formal parameter as an array in the function definition. You can declare it in one of the following two ways:
Method 1
Formal parameter with specified array size:
void myFunction(param [10]int)
{
.
.
.
}
Method 2
Formal parameter without specified array size:
void myFunction(param []int)
{
.
.
.
}
Example
Let's look at the following example. The function receives an integer array parameter and another parameter specifying the number of elements in the array, and returns the average:
Example
func getAverage(arr []int, size int) float32
{
var i int
var avg, sum float32
for i = 0; i < size; ++i {
sum += arr[i]
}
avg = sum / size
return avg;
}
Next, let's call this function:
Example
package main
import "fmt"
func main() {
/* Array length is 5 */
var balance = [5]int {1000, 2, 3, 17, 50}
var avg float32
/* Pass the array to the function */
avg = getAverage(balance, 5)
/* Print the returned average */
fmt.Printf("Average value is: %f ", avg)
}
func getAverage(arr [5]int, size int) float32 {
var i, sum int
var avg float32
for i = 0; i < size; i++ {
sum += arr[i]
}
avg = float32(sum) / float32(size)
return avg;
}
The output of the above example is:
Average value is: 214.399994
In the above example, we used a formal parameter without specifying the array size.
Floating-point calculations may have some deviations in the output. You can also convert to integers to set the precision.
Example
package main
import (
"fmt"
)
func main() {
a := 1.69
b := 1.7
c := a * b // The result should be 2.873
fmt.Println(c) // Outputs 2.8729999999999998
}
Setting a fixed precision:
Example
package main
import (
"fmt"
)
func main() {
a := 1690 // Represents 1.69
b := 1700 // Represents 1.70
c := a * b // The result should be 2873000 representing 2.873
fmt.Println(c) // Internal encoding
fmt.Println(float64(c) / 1000000) // Display
}