From 8518f4920f1a61a242ef922e854cb8b85ada2a96 Mon Sep 17 00:00:00 2001 From: mohdjishin Date: Wed, 27 Mar 2024 11:21:51 +0530 Subject: [PATCH] updated go generics --- source/_posts/go.md | 36 +++++++++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/source/_posts/go.md b/source/_posts/go.md index 0941fa4..ad7fdf3 100644 --- a/source/_posts/go.md +++ b/source/_posts/go.md @@ -1008,16 +1008,12 @@ func main() { } ``` +Go generics {.cols-2} ------------- -### Go generics - +### example 1 ```go -package main - -import "fmt" - // comparable represents types that can be compared. type comparable interface { int | float64 | string @@ -1034,15 +1030,37 @@ func Max[T comparable](a, b T) T { func main() { // Find the maximum of two integers. maxInt := Max(10, 20) - fmt.Println("Max integer:", maxInt) // Output: Max integer: 20 + fmt.Println("Max integer:", maxInt) // Find the maximum of two floats. maxFloat := Max(3.14, 2.71) - fmt.Println("Max float:", maxFloat) // Output: Max float: 3.14 + fmt.Println("Max float:", maxFloat) // Find the maximum of two strings. maxString := Max("apple", "banana") - fmt.Println("Max string:", maxString) // Output: Max string: banana + fmt.Println("Max string:", maxString) +} + +``` + +### example 2 +```go + +// Pair[T, U] represents a generic pair of values. +type Pair[T, U any] struct { + First T + Second U +} + +func main() { + pair := Pair[int, string]{First: 42, Second: "hello"} + + fmt.Println("First:", pair.First) + fmt.Println("Second:", pair.Second) + + // Print the types of the values in the pair. + fmt.Println("Type of First:", reflect.TypeOf(pair.First)) + fmt.Println("Type of Second:", reflect.TypeOf(pair.Second)) } ```