2.31. Go language passes an array to a function

发布时间 : 2025-10-25 13:32:54 UTC      

Page Views: 9 views

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:

2.31.1. Mode one #

The parameter sets the array size:

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

2.31.2. Mode two #

The parameter does not set the array size:

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

2.31.3. 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 } 
《地理信息系统原理、技术与方法》  97

最近几年来,地理信息系统无论是在理论上还是应用上都处在一个飞速发展的阶段。 GIS被应用于多个领域的建模和决策支持,如城市管理、区划、环境整治等等,地理信息成为信息时代重要的组成部分之一; “数字地球”概念的提出,更进一步推动了作为其技术支撑的GIS的发展。 与此同时,一些学者致力于相关的理论研究,如空间感知、空间数据误差、空间关系的形式化等等。 这恰好说明了地理信息系统作为应用技术和学科的两个方面,并且这两个方面构成了相互促进的发展过程。