go go/book/learninggo

Go - Generics

A generic container can store elements of any type using type parameters. Below is an example implementation of a generic container.

package main
 
import "fmt"
 
// GenericContainer is a generic struct that holds a slice of type T.
type GenericContainer[T any] struct {
	elements []T
}
 
// Add adds an element to the container.
func (c *GenericContainer[T]) Add(element T) {
	c.elements = append(c.elements, element)
}
 
// Get returns an element at a specific index.
func (c *GenericContainer[T]) Get(index int) (T, bool) {
	if index < 0 || index >= len(c.elements) {
		var zeroValue T
		return zeroValue, false
	}
	return c.elements[index], true
}
 
// Size returns the number of elements in the container.
func (c *GenericContainer[T]) Size() int {
	return len(c.elements)
}
 
func main() {
	// Create an integer container
	intContainer := GenericContainer[int]{}
	intContainer.Add(10)
	intContainer.Add(20)
 
	// Retrieve an element
	val, exists := intContainer.Get(1)
	if exists {
		fmt.Println("Retrieved:", val) // Output: Retrieved: 20
	}
 
	// Create a string container
	stringContainer := GenericContainer[string]{}
	stringContainer.Add("Hello")
	stringContainer.Add("Go")
 
	// Retrieve an element
	strVal, exists := stringContainer.Get(0)
	if exists {
		fmt.Println("Retrieved:", strVal) // Output: Retrieved: Hello
	}
 
	fmt.Println("Size of intContainer:", intContainer.Size()) // Output: Size of intContainer: 2
	fmt.Println("Size of stringContainer:", stringContainer.Size()) // Output: Size of stringContainer: 2
}
  • Generics (T any)
    • The GenericContainer[T any] struct uses T, meaning it can store elements of any type.
    • any is a Go alias for interface{} but with compile-time type checking.
  • Methods on Generic Type (T)
    • Add(element T): Adds an element of type T to the slice.
    • Get(index int) (T, bool): Retrieves an element safely.
    • Size() int: Returns the count of elements.
  • Type Safety
    • Unlike interface{}, this approach ensures compile-time type checking, preventing unexpected type issues.