Merge pull request #511 from mohdjishin/go/update

updated go generics
This commit is contained in:
Fechin authored and GitHub committed 2024-03-28 12:13:49 +08:00
commit 503cf935af
1 file changed
+27 -9
+27 -9
View File
@@ -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))
}
```