Created
January 10, 2024 10:33
-
-
Save Tanmay451/214dd45d09ab585cd42f843cf065733d to your computer and use it in GitHub Desktop.
Generics, also known as parametric polymorphism, enable you to write code that operates on multiple types without explicitly specifying the types upfront. This leads to more concise, reusable, and type-safe code.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// In the PrintSlice function, T is a type parameter, and any is a type constraint. | |
// The any constraint is built into the language and allows any type to be used. | |
// The function can be called with any slice type, such as []int or []string. | |
package main | |
import "fmt" | |
// PrintSlice prints each element of a slice of any type. | |
func PrintSlice[T any](s []T) { | |
for _, v := range s { | |
fmt.Println(v) | |
} | |
} | |
func main() { | |
// Example usage with an int slice. | |
intSlice := []int{1, 2, 3} | |
PrintSlice[int](intSlice) | |
// Example usage with a string slice. | |
stringSlice := []string{"hello", "world"} | |
PrintSlice[string](stringSlice) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment