Generic functions are great, as we saw in the previous tutorial, but we can do more. We can also write generic types. What does that mean? You already

Generic types in Go — Bitfield Consulting

submited by
Style Pass
2024-10-31 11:00:08

Generic functions are great, as we saw in the previous tutorial, but we can do more. We can also write generic types. What does that mean?

You already know that, just as an int variable can only hold int values, a []int slice can only hold int elements. We wouldn’t want to have to also define SliceOfFloat, SliceOfString, and so on.

Could we write a generic type definition that takes a type parameter, just like a generic function? For example, could we make a slice of any type?

Just as we could define a function such as Len that takes a slice of an arbitrary element type, we’ve now given a name to a new type: a slice of E, for some type E.

And just as with generic functions, a generic type is always instantiated on some specific type when it’s used in a program. That is to say, a Bunch[int] will be a slice of int, a Bunch[string] will be a slice of strings, and so on.

Each of these is a distinct concrete type, as you’d expect, and we can write a Bunch literal by giving the type we want in square brackets:

Leave a Comment