package main
// Generic method to swap two elements in a slice
// Generic method in Go using type parameters
// Go generics are simple, powerful
import (
"fmt"
)
// Generic swap function
func Swap[T any](arr []T, i, j int) {
arr[i], arr[j] = arr[j], arr[i]
}
func main() {
// Integer slice
nums := []int{10, 20, 30, 40}
fmt.Println("Before swap (int):", nums)
Swap(nums, 1, 3)
fmt.Println("After swap (int):", nums)
fmt.Println()
// String slice
words := []string{"Go", "Python", "Java", "C#"}
fmt.Println("Before swap (string):", words)
Swap(words, 0, 2)
fmt.Println("After swap (string):", words)
fmt.Println()
// Float slice
floats := []float64{1.1, 2.2, 3.3, 4.4}
fmt.Println("Before swap (float):", floats)
Swap(floats, 2, 3)
fmt.Println("After swap (float):", floats)
}
/*
run:
Before swap (int): [10 20 30 40]
After swap (int): [10 40 30 20]
Before swap (string): [Go Python Java C#]
After swap (string): [Java Python Go C#]
Before swap (float): [1.1 2.2 3.3 4.4]
After swap (float): [1.1 2.2 4.4 3.3]
*/