{"id":834,"date":"2026-10-09T15:00:00","date_gmt":"2026-10-09T09:30:00","guid":{"rendered":"https:\/\/smitabharat.com\/blog\/go-generics-programs\/"},"modified":"2026-11-29T01:29:27","modified_gmt":"2026-11-28T19:59:27","slug":"go-generics-programs","status":"publish","type":"post","link":"https:\/\/smitabharat.com\/blog\/go-generics-programs\/","title":{"rendered":"Go Generics Programs with Output: Map, Filter, Reduce and Stack"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Go generics programs let you write one function or type that works for many types, such as int, float64 and string, without copying code. In this post, you will write fifteen short programs with their exact output and the logic explained in comments, covering Max, Map, Filter, Reduce, a generic stack, a set and custom constraints.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You should first finish our <a href=\"https:\/\/smitabharat.com\/blog\/go-function-programs\/\">Go function programs<\/a> and <a href=\"https:\/\/smitabharat.com\/blog\/go-interface-programs\/\">Go interface programs<\/a>, because constraints are written as interfaces. For the theory, read our <a href=\"https:\/\/smitabharat.com\/blog\/go-generics-examples\/\">Go generics examples guide<\/a>. All programs were tested on Go 1.27.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What are Go Generics Programs?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Go generics programs use type parameters. A type parameter is a placeholder type written in square brackets, like <code>[T any]<\/code>. When you call the function, Go fills in the real type for you.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Think of a cookie cutter. The shape stays the same, but you can press it into chocolate dough, plain dough or ginger dough. A generic function is the cutter, and the type is the dough.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why Go Generics Programs Matter<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Before generics, you had to write <code>MaxInt<\/code>, <code>MaxFloat<\/code> and <code>MaxString<\/code> as three separate functions, or use <code>any<\/code> and lose type safety. Go generics programs fix both problems.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Less code:<\/strong> one <code>Map<\/code> function works for every slice type.<\/li>\n\n\n<li><strong>Type safety:<\/strong> the compiler still checks every call, so no runtime type checks.<\/li>\n\n\n<li><strong>Reusable types:<\/strong> one <code>Stack[T]<\/code> works for ints, strings or structs.<\/li>\n\n\n<li><strong>Interviews:<\/strong> Map, Filter, Reduce and a generic stack are among the most asked Go programs.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">How Go Generics Programs Work<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A generic function has two lists. The type parameter list in square brackets names the types, and the normal list in round brackets names the values. Each type parameter has a constraint that says which types are allowed.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-generics-programs-diagram-1-1024x640.png\" alt=\"Go generics programs diagram showing one generic function used with int, float64 and string\" class=\"wp-image-832\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-generics-programs-diagram-1-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-generics-programs-diagram-1-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-generics-programs-diagram-1-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-generics-programs-diagram-1-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-generics-programs-diagram-1-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">One generic function, many types: Go checks each call at compile time and fills in the real type.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The table below lists the common constraints used in this post.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Constraint<\/th><th>Where<\/th><th>Allows<\/th><\/tr><\/thead><tbody><tr><td>any<\/td><td>built in<\/td><td>Every type<\/td><\/tr><tr><td>comparable<\/td><td>built in<\/td><td>Types that work with == and !=<\/td><\/tr><tr><td>cmp.Ordered<\/td><td>cmp package<\/td><td>Types that work with &lt; and &gt;<\/td><\/tr><tr><td>~int<\/td><td>your own interface<\/td><td>int and any type built on int<\/td><\/tr><tr><td>Number<\/td><td>your own interface<\/td><td>A list of number types<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Basic Go Generics Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These first Go generics programs show a generic function, type inference and the cmp.Ordered constraint. Start with Program 1, because it is the smallest generic function you can write.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 1: Your First Generic Function<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ PrintAll prints every item of a slice, whatever the item type is.\n\/\/ [T any] means \"T can be any type\". T is the type parameter.\nfunc PrintAll[T any](items []T) {\n    for _, item := range items { \/\/ _ skips the index we do not need\n        fmt.Print(item, \" \")\n    }\n    fmt.Println()\n}\n\nfunc main() {\n    PrintAll([]int{1, 2, 3})               \/\/ here T is int\n    PrintAll([]string{\"red\", \"green\"})     \/\/ here T is string\n    PrintAll([]float64{9.5, 7.25})         \/\/ here T is float64\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>1 2 3 \nred green \n9.5 7.25 <\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You write <code>PrintAll<\/code> once, and it works for three slice types. When you call it, Go looks at the slice and fills in <code>T<\/code> for you. So you do not need a separate function for ints, strings and floats.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 2: Generic Max with cmp.Ordered<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"cmp\"\n    \"fmt\"\n)\n\n\/\/ Max returns the bigger of two values.\n\/\/ T is the type parameter, cmp.Ordered is its constraint: it allows &lt; and &gt;.\nfunc Max[T cmp.Ordered](first, second T) T {\n    if first &gt; second {\n        return first\n    }\n    return second\n}\n\nfunc main() {\n    fmt.Println(Max(3, 7))            \/\/ T is inferred as int\n    fmt.Println(Max(2.5, 1.5))        \/\/ T is inferred as float64\n    fmt.Println(Max(\"apple\", \"kiwi\")) \/\/ strings compare letter by letter\n    fmt.Println(Max[int](10, 4))      \/\/ you can also pass T yourself\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>7\n2.5\nkiwi\n10<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Go looks at the arguments and works out <code>T<\/code> for you. This is called type inference. Both arguments must have the same type, because they are both <code>T<\/code>. &#8220;kiwi&#8221; wins because &#8220;k&#8221; comes after &#8220;a&#8221;.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 3: Find an Item with comparable<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Index returns the position of target in items, or -1 if it is missing.\n\/\/ comparable allows == so we can compare items.\nfunc Index[T comparable](items []T, target T) int {\n    for i, item := range items { \/\/ i is the position, item is the value\n        if item == target {\n            return i\n        }\n    }\n    return -1 \/\/ not found\n}\n\nfunc main() {\n    fmt.Println(Index([]int{10, 20, 30}, 20))\n    fmt.Println(Index([]string{\"go\", \"java\"}, \"rust\"))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>1\n-1<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The loop checks each item with <code>==<\/code> and returns its position when it matches. If the loop ends with no match, the function returns -1. The standard library already has <code>slices.Index<\/code>, which works the same way, but writing it yourself is a common interview warm-up.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 4: Sum Numbers with a Custom Constraint<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Number lists the types Sum accepts. | means \"or\".\n\/\/ The ~ means \"this type or any type built on it\".\ntype Number interface {\n    ~int | ~int64 | ~float64\n}\n\n\/\/ Rupees is a named type whose underlying type is int.\ntype Rupees int\n\n\/\/ Sum adds up all the numbers in the slice.\nfunc Sum[T Number](numbers []T) T {\n    var total T \/\/ zero value of T: 0 for numbers\n    for _, number := range numbers {\n        total += number \/\/ allowed because every type in Number supports +\n    }\n    return total\n}\n\nfunc main() {\n    fmt.Println(Sum([]int{1, 2, 3}))\n    fmt.Println(Sum([]float64{1.5, 2.25}))\n    fmt.Println(Sum([]Rupees{100, 250})) \/\/ works only because of ~int\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>6\n3.75\n350<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Number<\/code> is a constraint that lists the allowed types. Because every type in it supports <code>+<\/code>, the compiler lets you write <code>total += number<\/code>. Without the <code>~<\/code>, <code>Rupees<\/code> would not match <code>int<\/code>, and the last call would not compile.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Map, Filter and Reduce Go Generics Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Map, Filter and Reduce are the most asked Go generics programs in interviews. Each one takes a slice and a function.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-generics-programs-diagram-2-1024x640.png\" alt=\"Go generics programs flow of Map, Filter and Reduce on a slice of numbers\" class=\"wp-image-833\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-generics-programs-diagram-2-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-generics-programs-diagram-2-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-generics-programs-diagram-2-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-generics-programs-diagram-2-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-generics-programs-diagram-2-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption class=\"wp-element-caption\">Map changes every item, Filter keeps some items and Reduce combines all items into one value.<\/figcaption><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Program 5: Map a Slice to a New Type<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\n\/\/ Map applies change to every item and returns the new slice.\n\/\/ T is the input type and Result is the output type, so they can differ.\nfunc Map[T, Result any](items []T, change func(T) Result) []Result {\n    results := make([]Result, 0, len(items)) \/\/ empty slice with room for every item\n    for _, item := range items {\n        results = append(results, change(item)) \/\/ append adds to the end\n    }\n    return results\n}\n\n\/\/ square returns number times number.\nfunc square(number int) int {\n    return number * number\n}\n\n\/\/ label turns a number into a text label like \"item-1\".\nfunc label(number int) string {\n    return fmt.Sprint(\"item-\", number)\n}\n\nfunc main() {\n    numbers := []int{1, 2, 3}\n    squares := Map(numbers, square)\n    labels := Map(numbers, label)\n    upper := Map([]string{\"go\", \"api\"}, strings.ToUpper)\n\n    fmt.Println(squares)\n    fmt.Println(labels)\n    fmt.Println(upper)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[1 4 9]\n[item-1 item-2 item-3]\n[GO API]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Map<\/code> calls the function you pass on every item and collects the answers. The first call keeps ints, but the second call turns <code>[]int<\/code> into <code>[]string<\/code>. That is why <code>Map<\/code> needs two type parameters.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 6: Filter a Slice<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Filter keeps only the items where keep returns true.\nfunc Filter[T any](items []T, keep func(T) bool) []T {\n    var kept []T \/\/ starts empty (nil)\n    for _, item := range items {\n        if keep(item) {\n            kept = append(kept, item)\n        }\n    }\n    return kept\n}\n\n\/\/ isEven reports whether a number divides by 2 with nothing left over.\nfunc isEven(number int) bool {\n    return number%2 == 0\n}\n\n\/\/ isLong reports whether a word has more than 2 letters.\nfunc isLong(word string) bool {\n    return len(word) &gt; 2\n}\n\nfunc main() {\n    evens := Filter([]int{1, 2, 3, 4, 5, 6}, isEven)\n    longWords := Filter([]string{\"go\", \"rust\", \"c\", \"java\"}, isLong)\n\n    fmt.Println(evens)\n    fmt.Println(longWords)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[2 4 6]\n[rust java]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Filter<\/code> asks the <code>keep<\/code> function about each item. If the answer is true, the item goes into the new slice. So the original slice is not changed, and <code>Filter<\/code> builds a new one.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 7: Reduce a Slice to One Value<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Reduce walks the slice and combines each item into one result.\n\/\/ start is the first value of the result.\nfunc Reduce[T, Result any](items []T, start Result, combine func(Result, T) Result) Result {\n    result := start\n    for _, item := range items {\n        result = combine(result, item)\n    }\n    return result\n}\n\n\/\/ add returns the running total plus the next number.\nfunc add(total, number int) int {\n    return total + number\n}\n\n\/\/ multiply returns the running product times the next number.\nfunc multiply(product, number int) int {\n    return product * number\n}\n\n\/\/ addLength returns the running count plus the length of the next word.\nfunc addLength(count int, word string) int {\n    return count + len(word)\n}\n\nfunc main() {\n    numbers := []int{1, 2, 3, 4}\n    total := Reduce(numbers, 0, add)\n    product := Reduce(numbers, 1, multiply)\n    letters := Reduce([]string{\"go\", \"is\", \"fun\"}, 0, addLength)\n\n    fmt.Println(total, product, letters)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>10 24 7<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Reduce<\/code> starts with the <code>start<\/code> value and then folds in each item, one by one. For the total, that is 0+1+2+3+4. The result type can differ from the item type, so in the last call the items are strings but the result is an int.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 8: Chain Map, Filter and Reduce<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Map, Filter and Reduce are the same as in Programs 5 to 7.\nfunc Map[T, Result any](items []T, change func(T) Result) []Result {\n    results := make([]Result, 0, len(items))\n    for _, item := range items {\n        results = append(results, change(item))\n    }\n    return results\n}\n\nfunc Filter[T any](items []T, keep func(T) bool) []T {\n    var kept []T\n    for _, item := range items {\n        if keep(item) {\n            kept = append(kept, item)\n        }\n    }\n    return kept\n}\n\nfunc Reduce[T, Result any](items []T, start Result, combine func(Result, T) Result) Result {\n    result := start\n    for _, item := range items {\n        result = combine(result, item)\n    }\n    return result\n}\n\n\/\/ Order is one item a customer bought.\ntype Order struct {\n    Item  string\n    Price int\n    Paid  bool\n}\n\n\/\/ isPaid reports whether the order was paid.\nfunc isPaid(order Order) bool { return order.Paid }\n\n\/\/ getPrice returns the price of the order.\nfunc getPrice(order Order) int { return order.Price }\n\n\/\/ add returns the running total plus one price.\nfunc add(total, price int) int { return total + price }\n\nfunc main() {\n    orders := []Order{{\"pen\", 20, true}, {\"book\", 300, false}, {\"bag\", 500, true}}\n\n    paid := Filter(orders, isPaid)  \/\/ Step 1: keep paid orders\n    prices := Map(paid, getPrice)   \/\/ Step 2: take the price\n    total := Reduce(prices, 0, add) \/\/ Step 3: add them up\n\n    fmt.Println(\"paid total:\", total)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>paid total: 520<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This is a real backend task: total the paid orders. First, <code>Filter<\/code> drops the unpaid book. Then <code>Map<\/code> turns the two orders into prices, and <code>Reduce<\/code> adds 20 and 500. Each step is small and easy to test on its own.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Generic Types in Go Generics Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Functions are not the only thing that can be generic. A struct can have type parameters too, and many real Go generics programs use generic containers like these.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 9: A Simple Generic Box<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Box holds one value of any type T.\ntype Box[T any] struct {\n    Content T\n}\n\nfunc main() {\n    numberBox := Box[int]{Content: 42}      \/\/ a Box that holds an int\n    wordBox := Box[string]{Content: \"gift\"} \/\/ a Box that holds a string\n\n    fmt.Println(numberBox.Content + 1)      \/\/ works because Content is an int\n    fmt.Println(wordBox.Content + \" card\")  \/\/ works because Content is a string\n    fmt.Printf(\"%+v\\n\", numberBox)          \/\/ %+v prints field names too\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>43\ngift card\n{Content:42}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Box[T]<\/code> is a generic type, so you choose <code>T<\/code> when you create a value. <code>Box[int]<\/code> holds an int, and <code>Box[string]<\/code> holds a string. Because Go knows the real type, <code>+ 1<\/code> and <code>+ \" card\"<\/code> both compile.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 10: A Generic Stack<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Stack holds items of one type T, last in, first out.\ntype Stack[T any] struct {\n    items []T\n}\n\n\/\/ Push puts an item on top of the stack.\nfunc (stack *Stack[T]) Push(item T) {\n    stack.items = append(stack.items, item)\n}\n\n\/\/ Pop returns the top item and true, or the zero value and false.\nfunc (stack *Stack[T]) Pop() (T, bool) {\n    var zero T \/\/ the zero value of T: \"\" for strings, 0 for ints\n    if len(stack.items) == 0 {\n        return zero, false \/\/ empty stack: nothing to pop\n    }\n    last := len(stack.items) - 1\n    item := stack.items[last]\n    stack.items = stack.items[:last] \/\/ [:last] keeps everything before the top\n    return item, true\n}\n\n\/\/ Len returns how many items are on the stack.\nfunc (stack *Stack[T]) Len() int {\n    return len(stack.items)\n}\n\nfunc main() {\n    var letters Stack[string]\n    letters.Push(\"a\")\n    letters.Push(\"b\")\n    letters.Push(\"c\")\n\n    for letters.Len() &gt; 0 {\n        letter, _ := letters.Pop()\n        fmt.Print(letter, \" \")\n    }\n    fmt.Println()\n\n    _, ok := letters.Pop() \/\/ ok is false when nothing was popped\n    fmt.Println(\"pop on empty:\", ok)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>c b a \npop on empty: false<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Push<\/code> adds to the end of the slice, and <code>Pop<\/code> takes from the end, so the last item in is the first out. <code>var zero T<\/code> gives the zero value of any type: &#8220;&#8221; for strings, 0 for ints and nil for pointers. This trick appears in almost every generic container.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 11: A Generic Set<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"fmt\"\n    \"slices\"\n)\n\n\/\/ Set uses a map with empty struct values, which take no memory.\ntype Set[T comparable] map[T]struct{}\n\n\/\/ Add puts a value in the set.\nfunc (set Set[T]) Add(value T) {\n    set[value] = struct{}{} \/\/ struct{}{} is an empty value\n}\n\n\/\/ Has reports whether the value is in the set.\nfunc (set Set[T]) Has(value T) bool {\n    _, ok := set[value] \/\/ ok is true if the key exists\n    return ok\n}\n\nfunc main() {\n    tags := Set[string]{}\n    for _, tag := range []string{\"go\", \"api\", \"go\", \"db\", \"api\"} {\n        tags.Add(tag) \/\/ duplicates are ignored by the map\n    }\n\n    fmt.Println(len(tags), tags.Has(\"db\"), tags.Has(\"java\"))\n\n    sortedTags := make([]string, 0, len(tags))\n    for tag := range tags {\n        sortedTags = append(sortedTags, tag)\n    }\n    slices.Sort(sortedTags) \/\/ map order is random, so sort before printing\n    fmt.Println(sortedTags)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>3 true false\n[api db go]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">A map can hold each key only once, so adding &#8220;go&#8221; twice keeps one copy. That is why the set has 3 tags. The key type must be <code>comparable<\/code>, because map keys are compared with <code>==<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 12: A Generic Pair and Sorted Map Keys<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"cmp\"\n    \"fmt\"\n    \"maps\"\n    \"slices\"\n)\n\n\/\/ Pair holds a key and a value of different types.\ntype Pair[K comparable, V any] struct {\n    Key   K\n    Value V\n}\n\n\/\/ SortedPairs turns a map into pairs ordered by key.\nfunc SortedPairs[K cmp.Ordered, V any](table map[K]V) []Pair[K, V] {\n    var pairs []Pair[K, V]\n    sortedKeys := slices.Sorted(maps.Keys(table)) \/\/ keys in sorted order\n    for _, key := range sortedKeys {\n        pairs = append(pairs, Pair[K, V]{Key: key, Value: table[key]})\n    }\n    return pairs\n}\n\nfunc main() {\n    stock := map[string]int{\"pen\": 40, \"bag\": 5, \"ink\": 12}\n    for _, pair := range SortedPairs(stock) {\n        fmt.Println(pair.Key, pair.Value)\n    }\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>bag 5\nink 12\npen 40<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">First, <code>maps.Keys<\/code> returns an iterator over the keys, and <code>slices.Sorted<\/code> collects it into a sorted slice. Then the loop builds one <code>Pair<\/code> for each key, in that order. So the output is always sorted, even though map order is random.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Most Asked Interview Go Generics Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These Go generics programs come up again and again in coding rounds.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 13: Reverse Any Slice<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Reverse swaps items from both ends, moving inwards.\nfunc Reverse[T any](items []T) {\n    for i := 0; i &lt; len(items)\/2; i++ { \/\/ only walk to the middle\n        j := len(items) - 1 - i \/\/ the matching position from the end\n        items[i], items[j] = items[j], items[i] \/\/ swap the two items\n    }\n}\n\nfunc main() {\n    numbers := []int{1, 2, 3, 4, 5}\n    names := []string{\"asha\", \"ravi\", \"meera\"}\n    Reverse(numbers)\n    Reverse(names)\n    fmt.Println(numbers, names)\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[5 4 3 2 1] [meera ravi asha]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The loop swaps the first and last items, then the second and second-last, and so on. It stops at the middle, or it would swap everything back. The swap works in place, so no new slice is created. <code>slices.Reverse<\/code> in the standard library does the same job.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 14: Remove Duplicates and Keep the Order<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Unique keeps the first copy of each item, in the original order.\nfunc Unique[T comparable](items []T) []T {\n    seen := make(map[T]bool) \/\/ remembers items we already kept\n    var unique []T\n    for _, item := range items {\n        if !seen[item] { \/\/ first time we see this item\n            seen[item] = true\n            unique = append(unique, item)\n        }\n    }\n    return unique\n}\n\nfunc main() {\n    fmt.Println(Unique([]int{3, 1, 3, 2, 1}))\n    fmt.Println(Unique([]string{\"b\", \"a\", \"b\"}))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[3 1 2]\n[b a]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The map remembers what we have seen, and the slice keeps the order. When an item shows up again, <code>seen<\/code> is already true, so it is skipped. This runs in one pass, so it is O(n).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Program 15: Min of a Slice with an Error for Empty Input<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport (\n    \"cmp\"\n    \"errors\"\n    \"fmt\"\n)\n\n\/\/ ErrEmpty is the error we return for an empty slice.\nvar ErrEmpty = errors.New(\"empty slice\")\n\n\/\/ MinOf returns the smallest item, or an error if there is none.\nfunc MinOf[T cmp.Ordered](items []T) (T, error) {\n    var zero T\n    if len(items) == 0 {\n        return zero, ErrEmpty \/\/ no items: return zero value and an error\n    }\n    smallest := items[0]\n    for _, item := range items[1:] { \/\/ [1:] means \"from the second item on\"\n        smallest = min(smallest, item) \/\/ built-in min works with ordered types\n    }\n    return smallest, nil \/\/ nil means \"no error\"\n}\n\nfunc main() {\n    fmt.Println(MinOf([]int{7, 2, 9}))\n    fmt.Println(MinOf([]string{\"pear\", \"fig\"}))\n    fmt.Println(MinOf([]float64{}))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2 &lt;nil&gt;\nfig &lt;nil&gt;\n0 empty slice<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The function starts with the first item and keeps the smaller one as it walks the rest. For an empty slice, it returns the zero value and <code>ErrEmpty<\/code>. Returning an error is safer than returning 0, because 0 could also be a real answer.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Generics vs Interfaces in Go Generics Programs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Both features let one piece of code work with many types, but they solve different problems. The table below compares them.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>Generics<\/th><th>Interfaces<\/th><\/tr><\/thead><tbody><tr><td>Type known at<\/td><td>Compile time<\/td><td>Runtime<\/td><\/tr><tr><td>Best for<\/td><td>Containers and slice helpers<\/td><td>Different behaviour per type<\/td><\/tr><tr><td>Example<\/td><td>Stack[T], Map, Filter<\/td><td>io.Reader, Shape with Area()<\/td><\/tr><tr><td>Type checks<\/td><td>Done by the compiler<\/td><td>Type assertions at runtime<\/td><\/tr><tr><td>Return type<\/td><td>The same T you passed<\/td><td>Often the interface type<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">A simple rule helps: if the code does the same thing for every type, write Go generics programs. If each type behaves differently, use an interface.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common Mistakes in Go Generics Programs<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Using any when you need ==:<\/strong> <code>any<\/code> does not allow <code>==<\/code>, so use <code>comparable<\/code>.<\/li>\n\n\n<li><strong>Using comparable when you need &lt;:<\/strong> sorting needs <code>cmp.Ordered<\/code>.<\/li>\n\n\n<li><strong>Forgetting the ~:<\/strong> a named type like <code>Rupees<\/code> will not match <code>int<\/code> without <code>~int<\/code>.<\/li>\n\n\n<li><strong>Generic methods:<\/strong> methods cannot have their own type parameters, only the type can.<\/li>\n\n\n<li><strong>Making everything generic:<\/strong> if only one type is ever used, a normal function is clearer.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Best Practices for Go Generics Programs<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Check the standard library first:<\/strong> <code>slices<\/code>, <code>maps<\/code> and <code>cmp<\/code> already have many helpers.<\/li>\n\n\n<li><strong>Use the loosest constraint that works<\/strong>, so more types can use your code.<\/li>\n\n\n<li><strong>Use short names<\/strong> like T, K and V for type parameters.<\/li>\n\n\n<li><strong>Return the zero value with ok or error<\/strong> when there is no result.<\/li>\n\n\n<li><strong>Write generic code after you repeat yourself<\/strong>, not before.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Go Generics Programs Interview Questions and Answers<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These are the generics questions interviewers ask most, and they build on the Go generics programs above. Each code answer is complete, with real output from Go 1.27.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Basics Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q1. In which Go version did generics arrive?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Generics arrived in Go 1.18, released in March 2022. Type parameters, constraints and the <code>any<\/code> and <code>comparable<\/code> names came with it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q2. What is the difference between any and interface{}?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There is no difference. <code>any<\/code> is an alias for <code>interface{}<\/code>, added in Go 1.18 to make code shorter to read.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q3. What does the ~ symbol mean in a constraint?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>~int<\/code> means &#8220;int or any type whose underlying type is int&#8221;. Without it, only <code>int<\/code> itself matches.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q4. Why does this code not compile?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Equal tries to compare two values of any type.\nfunc Equal[T any](first, second T) bool {\n    return first == second \/\/ any does not promise that == works\n}\n\nfunc main() {\n    fmt.Println(Equal(1, 1))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>incomparable types in type set<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Change the constraint to <code>comparable<\/code> and the code compiles and prints <code>true<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Constraint Questions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q5. Can a method have its own type parameters?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">No. Only the type can have type parameters, like <code>Stack[T]<\/code>. A method such as <code>func (s *Stack[T]) Map[U any]()<\/code> is not allowed, so write <code>Map<\/code> as a normal function instead.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q6. What is cmp.Ordered?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is a constraint in the <code>cmp<\/code> package that includes all integer, float and string types. These are the types that support <code>&lt;<\/code>, <code>&lt;=<\/code>, <code>&gt;<\/code> and <code>&gt;=<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q7. How do you get the zero value of a type parameter?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Declare <code>var zero T<\/code> and return it. You can also write <code>*new(T)<\/code>, but <code>var zero T<\/code> is easier to read.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q8. What does this program print?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Describe returns the name of the real type behind T.\nfunc Describe[T any](value T) string {\n    return fmt.Sprintf(\"%T\", value) \/\/ %T prints the real type of value\n}\n\nfunc main() {\n    fmt.Println(Describe(42), Describe(\"hi\"), Describe([]bool{true}))\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>int string []bool<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Inside a generic function, <code>T<\/code> is the real type of the call, so <code>%T<\/code> prints <code>int<\/code>, <code>string<\/code> and <code>[]bool<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Design Questions on Go Generics Programs<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q9. When should you not use generics?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not use generics when each type needs different behaviour. That is a job for interfaces. Also skip them when only one type is used, because a plain function is simpler.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q10. Are generics slower than normal code?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Usually not by a noticeable amount. Go compiles generic code with a method called GC shape stenciling, which shares code between types of the same shape. For hot paths, measure with a benchmark.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q11. How do you write a constraint that needs a method?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Put the method in the constraint interface, for example <code>type Stringer interface { String() string }<\/code>. Then <code>func Join[T Stringer](items []T)<\/code> can call <code>item.String()<\/code> on every item.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Q12. What does this program print?<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package main\n\nimport \"fmt\"\n\n\/\/ Box holds one value of type T.\ntype Box[T any] struct {\n    Value T\n}\n\n\/\/ Get returns the value inside the box.\nfunc (box Box[T]) Get() T {\n    return box.Value\n}\n\nfunc main() {\n    numberBox := Box[int]{Value: 5}\n    wordBox := Box[string]{Value: \"go\"}\n    fmt.Println(numberBox.Get()+1, wordBox.Get()+\"lang\")\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>6 golang<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Box[int]<\/code> and <code>Box[string]<\/code> are two different types. <code>Get<\/code> returns the right type each time, so <code>+1<\/code> and <code>+\"lang\"<\/code> both compile.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Practice Task<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To practise Go generics programs, write a generic <code>GroupBy[T any, K comparable](items []T, key func(T) K) map[K][]T<\/code> function. Use it to group a list of words by their length, then print the groups with the keys in sorted order. Hint: use <code>slices.Sorted(maps.Keys(m))<\/code> to sort the keys.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Official Resources<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/go.dev\/doc\/tutorial\/generics\">Tutorial: Getting started with generics<\/a><\/li>\n\n\n<li><a href=\"https:\/\/go.dev\/blog\/intro-generics\">An Introduction To Generics on the Go blog<\/a><\/li>\n\n\n<li><a href=\"https:\/\/pkg.go.dev\/cmp\">cmp package documentation<\/a><\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Quick Recap<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Go generics programs use type parameters like <code>[T any]<\/code> so one function works for many types.<\/li>\n\n\n<li><code>comparable<\/code> allows <code>==<\/code>, and <code>cmp.Ordered<\/code> allows <code>&lt;<\/code> and <code>&gt;<\/code>.<\/li>\n\n\n<li>Map, Filter and Reduce are the most asked generic helpers.<\/li>\n\n\n<li>Generic types like <code>Stack[T]<\/code> and <code>Set[T]<\/code> reuse one design for many types.<\/li>\n\n\n<li>Use <code>var zero T<\/code> with an ok flag or error when there is nothing to return.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s Next?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Next, we test your Go knowledge with programs that trick most people. Read <a href=\"https:\/\/smitabharat.com\/blog\/go-tricky-output-programs\/\">Go tricky output programs<\/a>, covering defer, closures, slices and nil interfaces. For more practice, see the <a href=\"https:\/\/smitabharat.com\/blog\/go-generics-interview-questions-part-11\/\">Go generics interview questions<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Go generics programs let you write one function or type that works for many types, such as int, float64 and string, without copying code.&hellip;<\/p>\n","protected":false},"author":1,"featured_media":831,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_swapz_level":"","_swapz_series_part":0,"_swapz_hide_toc":false,"_swapz_hide_featured":false,"_swapz_description":"","footnotes":""},"categories":[106],"tags":[96,40,95,11,104],"swapz_series":[],"class_list":["post-834","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-go-programs","tag-beginner","tag-go-generics","tag-go-interview-questions","tag-go-lang","tag-go-programs"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Go Generics Programs: Map, Filter, Reduce, Stack<\/title>\n<meta name=\"description\" content=\"Go generics programs with output: Max with cmp.Ordered, Map, Filter, Reduce, a generic stack and set, custom constraints, plus generics interview Q&amp;A.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/smitabharat.com\/blog\/go-generics-programs\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Go Generics Programs: Map, Filter, Reduce, Stack\" \/>\n<meta property=\"og:description\" content=\"Go generics programs with output: Max with cmp.Ordered, Map, Filter, Reduce, a generic stack and set, custom constraints, plus generics interview Q&amp;A.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/smitabharat.com\/blog\/go-generics-programs\/\" \/>\n<meta property=\"og:site_name\" content=\"Smita Bharat - Blog\" \/>\n<meta property=\"article:published_time\" content=\"2026-10-09T09:30:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-11-28T19:59:27+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-generics-programs-featured.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2400\" \/>\n\t<meta property=\"og:image:height\" content=\"1260\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Smita\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Smita\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"19 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-generics-programs\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-generics-programs\\\/\"},\"author\":{\"name\":\"Smita\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"headline\":\"Go Generics Programs with Output: Map, Filter, Reduce and Stack\",\"datePublished\":\"2026-10-09T09:30:00+00:00\",\"dateModified\":\"2026-11-28T19:59:27+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-generics-programs\\\/\"},\"wordCount\":1869,\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-generics-programs\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-generics-programs-featured.png\",\"keywords\":[\"Beginner\",\"Go Generics\",\"Go Interview Questions\",\"Go Lang\",\"Go Programs\"],\"articleSection\":[\"Go Programs\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-generics-programs\\\/\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-generics-programs\\\/\",\"name\":\"Go Generics Programs: Map, Filter, Reduce, Stack\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-generics-programs\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-generics-programs\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-generics-programs-featured.png\",\"datePublished\":\"2026-10-09T09:30:00+00:00\",\"dateModified\":\"2026-11-28T19:59:27+00:00\",\"description\":\"Go generics programs with output: Max with cmp.Ordered, Map, Filter, Reduce, a generic stack and set, custom constraints, plus generics interview Q&A.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-generics-programs\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-generics-programs\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-generics-programs\\\/#primaryimage\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-generics-programs-featured.png\",\"contentUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-generics-programs-featured.png\",\"width\":2400,\"height\":1260,\"caption\":\"Go Generics Programs featured image: Map, Filter, Reduce and stack output\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-generics-programs\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Go Generics Programs with Output: Map, Filter, Reduce and Stack\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\",\"name\":\"Smita Bharat Blog\",\"description\":\"Golang &amp; Backend Development Tutorials and Interview Questions\",\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"alternateName\":\"Smita Bharat\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\",\"name\":\"Smita\",\"logo\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/smitabharat.com\\\/blog\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Go Generics Programs: Map, Filter, Reduce, Stack","description":"Go generics programs with output: Max with cmp.Ordered, Map, Filter, Reduce, a generic stack and set, custom constraints, plus generics interview Q&A.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/smitabharat.com\/blog\/go-generics-programs\/","og_locale":"en_US","og_type":"article","og_title":"Go Generics Programs: Map, Filter, Reduce, Stack","og_description":"Go generics programs with output: Max with cmp.Ordered, Map, Filter, Reduce, a generic stack and set, custom constraints, plus generics interview Q&A.","og_url":"https:\/\/smitabharat.com\/blog\/go-generics-programs\/","og_site_name":"Smita Bharat - Blog","article_published_time":"2026-10-09T09:30:00+00:00","article_modified_time":"2026-11-28T19:59:27+00:00","og_image":[{"width":2400,"height":1260,"url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-generics-programs-featured.png","type":"image\/png"}],"author":"Smita","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Smita","Est. reading time":"19 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/smitabharat.com\/blog\/go-generics-programs\/#article","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/go-generics-programs\/"},"author":{"name":"Smita","@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"headline":"Go Generics Programs with Output: Map, Filter, Reduce and Stack","datePublished":"2026-10-09T09:30:00+00:00","dateModified":"2026-11-28T19:59:27+00:00","mainEntityOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-generics-programs\/"},"wordCount":1869,"publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-generics-programs\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-generics-programs-featured.png","keywords":["Beginner","Go Generics","Go Interview Questions","Go Lang","Go Programs"],"articleSection":["Go Programs"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/smitabharat.com\/blog\/go-generics-programs\/","url":"https:\/\/smitabharat.com\/blog\/go-generics-programs\/","name":"Go Generics Programs: Map, Filter, Reduce, Stack","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-generics-programs\/#primaryimage"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-generics-programs\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-generics-programs-featured.png","datePublished":"2026-10-09T09:30:00+00:00","dateModified":"2026-11-28T19:59:27+00:00","description":"Go generics programs with output: Max with cmp.Ordered, Map, Filter, Reduce, a generic stack and set, custom constraints, plus generics interview Q&A.","breadcrumb":{"@id":"https:\/\/smitabharat.com\/blog\/go-generics-programs\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/smitabharat.com\/blog\/go-generics-programs\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/smitabharat.com\/blog\/go-generics-programs\/#primaryimage","url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-generics-programs-featured.png","contentUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-generics-programs-featured.png","width":2400,"height":1260,"caption":"Go Generics Programs featured image: Map, Filter, Reduce and stack output"},{"@type":"BreadcrumbList","@id":"https:\/\/smitabharat.com\/blog\/go-generics-programs\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/smitabharat.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Go Generics Programs with Output: Map, Filter, Reduce and Stack"}]},{"@type":"WebSite","@id":"https:\/\/smitabharat.com\/blog\/#website","url":"https:\/\/smitabharat.com\/blog\/","name":"Smita Bharat Blog","description":"Golang &amp; Backend Development Tutorials and Interview Questions","publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"alternateName":"Smita Bharat","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/smitabharat.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339","name":"Smita","logo":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/image\/"},"sameAs":["https:\/\/smitabharat.com\/blog"]}]}},"_links":{"self":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/834","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/comments?post=834"}],"version-history":[{"count":1,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/834\/revisions"}],"predecessor-version":[{"id":897,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/834\/revisions\/897"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media\/831"}],"wp:attachment":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media?parent=834"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/categories?post=834"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/tags?post=834"},{"taxonomy":"swapz_series","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/swapz_series?post=834"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}