Saved Bookmarks
| 1. |
Write a Go program to swap variables in a list? |
|
Answer» CONSIDER we have num1=2, num2=3. To swap these two numbers, we can just WRITE: num1,num2 = num2, num1 The same logic can be extended to a list of variables as shown below: package mainimport "fmt"func swapContents(listObj []int) { for i, j := 0, len(listObj)-1; i < j; i, j = i+1, j-1 { listObj[i], listObj[j] = listObj[j], listObj[i] }}func MAIN() { listObj := []int{1, 2, 3} swapContents(listObj) fmt.Println(listObj)}The code results in the output: [3 2 1] |
|