DEV Community

Divyanshu Shekhar
Divyanshu Shekhar

Posted on

Golang Generics

The wait is finally over as Go has introduced its much-anticipated feature, Golang Generics, with the release of version 1.18. We’re thrilled to dive into this fascinating addition to the language and explore how Go has implemented generics. Join us on this journey as we unravel the inner workings of Golang Generics and witness the impact it can have on your code. So without further ado, let’s embark on this adventure together!

Understanding The Problem

To properly understand the concept of Golang Generics, it is essential to understand the problem they aim to solve. Let’s explore this by considering a simple example.

Imagine we have a simple Add() function that takes two integers and returns their sum:

func Add(a, b int) int {
    return a + b
}

func main() {
    fmt.Println(Add(1, 2))    // Output: 3
}
Enter fullscreen mode Exit fullscreen mode

This function works perfectly fine for integers, but what if we want it to accept float values as well? If we try to use a float value with our Add() function, we encounter an error:

func main() {
    fmt.Println(Add(1.1, 2))    // Error: cannot use 1.1 (untyped float constant) as int value in argument to Add
}
Enter fullscreen mode Exit fullscreen mode

Now, you might suggest using interfaces to solve this problem, but there’s a catch. We only want the Add() function to accept integer and float values, not any other types. Unfortunately, achieving this level of specificity is not possible with interfaces alone.

This is where Golang generics come into play.

What’s New in Go 1.18?

In the highly anticipated release of Go version 1.18, which followed seven months after the previous version 1.17, the language introduced a game-changing feature: generics. Fulfilling its compatibility promise, Go 1.18 ensures backward compatibility with Go 1, ensuring a smooth transition for developers.

So, what exactly do these generics bring to the table? Let’s delve into the three major advancements that accompany this release:

Defining Interface Types as Sets of Types
Type Parameters for Functions and Types
Type Inference
Exciting, isn’t it? So, fasten your seatbelts and get ready to witness the power of generics in Go 1.18!

What is a Generic Type?

In programming, a generic type is a type that can be used with multiple other types, allowing for code reusability and flexibility.

It serves as a template, enabling you to write functions and data structures that work seamlessly with various data types without duplicating code.

Generics Overview

In order to grasp the concept of generics in Go more effectively, let’s take a moment to gain an overview of how other programming languages, such as C++ and Java, implement generics. By comparing and contrasting these implementations, we can better understand the unique approach that Golang brings to the table.

In C++, generics are achieved through templates, which allow generic functions and classes to be created. Templates enable the definition of algorithms and data structures that can work with multiple types without sacrificing type safety.

template <typename T>
void swap(T& a, T& b) {
    T temp = a;
    a = b;
    b = temp;
}
Enter fullscreen mode Exit fullscreen mode

Here, T represents the generic type parameter, and it allows us to write a single swap function that works for various data types.

Java, on the other hand, introduced generics with the release of Java 5. Generics in Java are implemented using type erasure, a technique where type information is removed at runtime, making generics a compile-time feature.

public class Box<T> {
    private T value;

    public void setValue(T value) {
        this.value = value;
    }

    public T getValue() {
        return value;
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, T is the type parameter that allows the Box class to work with different types of values.

Now, let’s shift our focus back to Go and explore its take on generics.

Prerequisites

To get started with this tutorial, you’ll need:

Go version 1.18 or greater installed: Make sure you have Go installed on your system, preferably version 1.18 or a newer release.
Solid understanding of Go basics: Ensure that you have a good understanding of Go’s fundamental concepts, including struct types, for loops, slices, and interfaces.
With these prerequisites fulfilled, we’re all set to dive into the fascinating world of Golang generics. Let’s begin our coding journey together!

Golang Generics Syntax

In the world of Go, generics have made their grand entrance starting from version 1.18, adding a whole new level of flexibility and power to the language. Now, let’s dive into the syntax of Golang generics, exploring how they can be used with functions and types.

Golang Generic Function Syntax
To define a generic function in Go, we utilize the following syntax:

func FunctionName[T Constraint](a, b T) T {
    // Function Body
}
Enter fullscreen mode Exit fullscreen mode

In the above syntax, FunctionName represents the name of our generic function. The square brackets [T Constraint] indicate the use of a type parameter T, which can be any type constraint.

Inside the function parentheses (a, b T), we define the input parameters a and b of type T. The return type of the function is also T, denoted after the parentheses. You can replace T with any valid identifier that fits your needs.

Read full from original Post: Golang Generics. Find the blog on Google.

Top comments (0)