golang tutorial - Golang Array Arguements To Function | Go arrays as arguments to functions - golang - go programming language - google go - go language - go program - google language



Golang Arrays Arguements To Functions

  • To pass the single-dimension array as an argument in a function, you should declare the functions formal parameter as below.

Option -1

  • Static size of the array - Array with size below as 10
void wikitechy_Function(param [10]int)
{
.
.
.
}
click below button to copy the code. By - golang tutorial - team
golang , gopro , google go , golang tutorial , google language , go language , go programming language

Option -2

  • Dynamic Array size passed as parameters to the function
void wikitechy_Function(param []int)
{
.
.
.
}
click below button to copy the code. By - golang tutorial - team

Example

  • Go Function to calculate the average of given parameters passed as arguments in the form of arrays.
  • The return value is average of the given numbers
func Average(arr []int, int size) float32
{
   var i int
   var avg, sum float32  

   for i = 0; i < size; ++i {
      sum += arr[i]
   }

   avg = sum / size

   return avg;
}
click below button to copy the code. By - golang tutorial - team
  • Program for the function with array as arguments
package main

import "fmt"

func main() {
   /* an int array with 5 elements */
   var  balance = []int {1000, 2, 3, 17, 50}
   var avg float32

   /* pass array as an argument */
   avg = getAverage( balance, 5 ) ;

   /* output the returned value */
   fmt.Printf( "Average value is: %f ", avg );
}
func getAverage(arr []int, size int) float32 {
   var i,sum int
   var avg float32  

   for i = 0; i < size;i++ {
      sum += arr[i]
   }

   avg = float32(sum / size)

   return avg;
}
click below button to copy the code. By - golang tutorial - team

Output for the above code

Average value is: 214.400000

Related Searches to Go arrays as arguments to functions