|
| 1 | +package generics |
| 2 | + |
| 3 | +import "fmt" |
| 4 | + |
| 5 | +/* |
| 6 | +Genetics was added to golang for version `1.18`. Generics can also be known as |
| 7 | +`type parameters`. |
| 8 | +*/ |
| 9 | +func Run() { |
| 10 | + genericStruct() |
| 11 | + genericMapExample() |
| 12 | + /* |
| 13 | + When invoking generic functions, we can often rely on type inference. |
| 14 | + We don't have to specify the types for K and V when calling `sliceOfMapKeys` |
| 15 | + The go compiler can infer them for us. |
| 16 | + */ |
| 17 | + inferredGenericsExample() |
| 18 | +} |
| 19 | + |
| 20 | +func genericStruct() { |
| 21 | + elements := []int{1, 2, 3, 4} |
| 22 | + NewGenericStruct[int](elements...).Iterate() |
| 23 | + other := []string{"A", "B", "C"} |
| 24 | + NewGenericStruct[string](other...).Iterate() |
| 25 | +} |
| 26 | + |
| 27 | +func genericMapExample() { |
| 28 | + hash := make(map[int]string) |
| 29 | + hash[1] = "A" |
| 30 | + hash[2] = "B" |
| 31 | + hash[3] = "C" |
| 32 | + for _, key := range sliceOfMapKeys[int, string](hash) { |
| 33 | + fmt.Println(key) |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +func inferredGenericsExample() { |
| 38 | + hash := make(map[string]int) |
| 39 | + hash["foo"] = 10 |
| 40 | + hash["bar"] = 20 |
| 41 | + _ = sliceOfMapKeys(hash) |
| 42 | +} |
| 43 | + |
| 44 | +// A Generic function that returns a slice of its keys |
| 45 | +func sliceOfMapKeys[K comparable, V any](hash map[K]V) []K { |
| 46 | + container := make([]K, 0) |
| 47 | + // Ranging a map by default iterates the keys. |
| 48 | + for key := range hash { |
| 49 | + container = append(container, key) |
| 50 | + } |
| 51 | + return container |
| 52 | +} |
| 53 | + |
| 54 | +type GenericStruct[T any] struct { |
| 55 | + elements []T |
| 56 | +} |
| 57 | + |
| 58 | +func NewGenericStruct[T any](elements ...T) *GenericStruct[T] { |
| 59 | + store := make([]T, 0) |
| 60 | + store = append(store, elements...) |
| 61 | + return &GenericStruct[T]{ |
| 62 | + elements: store, |
| 63 | + } |
| 64 | + |
| 65 | +} |
| 66 | + |
| 67 | +// Defining methods on generic types as normal |
| 68 | +func (g *GenericStruct[T]) Iterate() { |
| 69 | + for _, element := range g.elements { |
| 70 | + fmt.Println(element) |
| 71 | + } |
| 72 | +} |
0 commit comments