Go language passes an array to a function


Release date:2023-09-15 Update date:2023-10-13 Editor:admin View counts:357

Label:

Go language passes an array to a function

If you want to pass an array parameter to a function, you need to declare the parameter as an array when the function is defined. We can declare it intwo ways:

Mode one

The parameter sets the array size:

void myFunction(param [10]int)
{
.
.
.
}

Mode two

The parameter does not set the array size:

void myFunction(param []int)
{
.
.
.
}

Example

Let’s take a look at the following example, where the function takes an integer array parameter, and another parameter specifies the number of array elements 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
   /* Array passed as a parameter to a function */
   avg = getAverage( balance, 5 ) ;
   /* Output the average value returned */
   fmt.Printf( "The 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 as follows:

The average value is: 214.399994

The parameter we used in the above example does not set the array size.

The floating point calculation output has a certain deviation, you can also convert the integer 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)  // The output is 2.8729999999999998
}

Set fixed precision:

Example

package main
import (
    "fmt"
)
func main() {
    a := 1690           // Represent 1.69
    b := 1700           // Represent 1.70
    c := a * b          // The result should be 2873000 representing 2.873
    fmt.Println(c)      // internal code
    fmt.Println(float64(c) / 1000000) // display
}

Powered by TorCMS (https://github.com/bukun/TorCMS).