Hey, Gophers and Rustaceans!

Today, we’ll compare Go and Rust generics. Go and Rust are both statically and strictly typed languages that are also compiled. They’re both gaining popularity, and many new apps are incorporating them. Some Java-based back-end systems are being ported to Go and Rust. Both are actively maintained and developed. As of this writing, the most recent version of Go is 1.18 and Rust is version 1.60. The Go version 1.18 includes a long-awaited feature called Generics. Lets start with Go’s Generics. Take note, this article will only cover the basics.

Generics in Go

This is the code sample of Generics in Go.

func test[T any] (arg T) T {
    return arg
}

The []T function signature combination with [T any] is our indication that tells the compiler the data type T will be determined at the execution time.

Those of you who came from Java probably expected it to use the good ol’ angle brackets <T>. They may have chosen square brackets [T] over angle brackets <T> for technical reasons.

Generics in Rust

Generics is the topic of generalizing types and functionalities to broader cases. This is extremely useful for reducing code duplication in many ways, but can call for rather involved syntax. Namely, being generic requires taking great care to specify over which types a generic type is actually considered valid. The simplest and most common use of generics is for type parameters. As cited in Rust By Example.

Code sample for Generics in Rust. Defining a generic function called gen that takes an argument and return T of any type.

fn gen<T>(arg: T) -> T { ... }

T has been specified as a generic type parameter using <T>.


Conclusion

The language developers made excellent decisions to improve the language. It’s natural to have pros and cons, so we programmers should be objective and avoid biases. This article was not written to demonstrate which generics implementation is superior. Respect the language developers’ design choices. Please correct me if I made a mistake in this article.


#Gophers #Rustaceans