When using golang for array operations, sometimes it is necessary to flip the array. So the question is, how to use golang to implement array flipping? This article will introduce two methods.
Method 1: Use for loop to flip array elements
Use for loop to flip array elements. The specific implementation steps are as follows:
The following is the specific code implementation:
package main import ( "fmt" ) func main() { arr := []int{1, 2, 3, 4, 5} n := len(arr) for i := 0; i < n/2; i++ { arr[i], arr[n-i-1] = arr[n-i-1], arr[i] } fmt.Println(arr) }
This code will output [5 4 3 2 1].
Method 2: Use the sort package to flip array elements
The sort package in golang provides the Reverse function, which can flip the array. The specific implementation steps are as follows:
The following is the specific code implementation:
package main import ( "fmt" "sort" ) func main() { arr := []int{1, 2, 3, 4, 5} sort.Sort(sort.Reverse(sort.IntSlice(arr))) fmt.Println(arr) }
This code will output [5 4 3 2 1].
Summary
Both methods can achieve flipping of array elements. Using a for loop is simpler and clearer, but using the sort package to implement the code is more concise and efficient. In actual development, the specific method to choose should be chosen based on actual needs and circumstances.
The above is the detailed content of golang array flip. For more information, please follow other related articles on the PHP Chinese website!