mirror of
https://github.com/Fechin/reference.git
synced 2026-11-20 21:23:11 +03:00
1 file changed
+27
-9
+27
-9
@@ -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))
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
Reference in new issue
Block a user