如何在Golang函数中返回数组?
在编程中,为了使代码更模块化、更易用和更易读,我们将代码分解成不同的函数。例如,我们必须在不同的地方交换两个数字,所以我们不进行就地交换,而是创建一个不同的函数并在任何需要的地方调用它。在某些用例中,我们需要一个函数一次返回多个值。为此,我们在编程中使用一种称为数组的数据结构,它只不过是多个相同类型值的集合。在本教程中,我们将学习如何在Golang函数中将数组作为参数返回。
示例
在这个例子中,我们将向函数传递一个整数类型的数组,然后对数组进行排序,最后返回排序后的数组。为了对数组进行排序,我们将使用**选择排序**算法。
算法
**步骤1:var array [5]int −** 声明一个大小为5,数据类型为int的变量。
**步骤2:array[0] = 45, array[1] = 9, array[2] = 99, array[3] = 900, array[4] = 801 −** 初始化数组的所有索引。
**步骤3:array = sortTheArray(array) −** 使用选择排序对数组进行排序。首先,我们调用函数并传递上面初始化的数组,然后对数组进行排序。
**for i := 0; i < len(array)−1; i++ { } −** 运行一个从0到数组长度-1的for循环。
**min_index := i −** 在每次迭代中创建一个变量来存储剩余元素中最小的数字的索引。
**for j := i + 1; j < len(array); j++ { } −** 运行一个从i+1到数组最后一个索引的内部循环。
**if array[j] < array[min_index] { min_index = j } −** 添加一个if语句来查找剩余元素中的最小元素并将索引存储在min_index中。
**if i != min_index { swap(&array[i], &array[min_index]) } −** 如果在内部循环中min_index的值发生更改,则在此处进行交换。
**步骤4:**打印排序后的数组。
示例
package main
import (
// fmt package provides the function to print anything
"fmt"
)
func swap(number1, number2 *int) {
// swapping both numbers using the third number
number3 := *number1
*number1 = *number2
*number2 = number3
}
// array is the argument in this function
func sortTheArray(array [5]int) [5]int {
fmt.Println("Sorting the array using the Selection sort algorithm.")
// running a for loop from 0 to 1 less than the array length
for i := 0; i < len(array)-1; i++ {
// declaring and initializing the variable that will store the index
// of minimum element in the remaining element
min_index := i
// running an inner loop on the elements after ith index
for j := i + 1; j < len(array); j++ {
// comparing the element with the element at min_index
if array[j] < array[min_index] {
min_index = j
}
}
// swapping the elements if i and min_index does not matches
if i != min_index {
swap(&array[i], &array[min_index])
}
}
return array
}
func main() {
// declaring the array of type string with size 5
var array [5]int
// initializing all the index of array
array[0] = 45
array[1] = 9
array[2] = 99
array[3] = 900
array[4] = 801
fmt.Println("Golang program to return an array in the function.")
fmt.Println("Array elements before sorting.")
for i := 0; i < len(array); i++ {
fmt.Printf("%d ", array[i])
}
fmt.Println()
// passing argument in the function and storing the returned
// sorted array in the array variable
array = sortTheArray(array)
fmt.Println("Array elements after sorting.")
for i := 0; i < len(array); i++ {
fmt.Printf("%d ", array[i])
}
fmt.Println()
}
输出
Golang program to return an array in the function. Array elements before sorting. 45 9 99 900 801 Sorting the array using the Selection sort algorithm. Array elements after sorting. 9 45 99 801 900
结论
这是一个在Golang函数中返回数组的示例,我们向函数传递了一个int类型的数组,然后使用选择排序对数组进行排序。排序后,我们最终返回了数组。要了解更多关于Go的信息,您可以浏览这些教程。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP