How to create a generic method in Go

2 Answers

0 votes
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]

*/

 



answered 3 hours ago by avibootz
0 votes
package main

// Generic Pair Function

import (
    "fmt"
)

func PrintPair[K any, V any](key K, value V) {
    fmt.Println(key, "=", value)
}

func main() {
    PrintPair("Age", 60)
    PrintPair(101, "Employee ID")
    PrintPair("Pi", 3.14159)
}



/*
run:

Age = 60
101 = Employee ID
Pi = 3.14159

*/

 



answered 3 hours ago by avibootz
...