DEV Community

Cover image for Generics in Golang 🚀
tj
tj

Posted on

3 2

Generics in Golang 🚀

Golang just released a beta version, offering a preview or atleast a working example of how to use generics and how it works with the compiler.


package main

import (
    "fmt"
)

func Writer[T string | int](w T) {
    fmt.Println(w)
}
func main() {
    Writer("Hello")
    Writer(1)
}
Enter fullscreen mode Exit fullscreen mode

as simple as it looks, it's really unique and powerful.
It has both the easy and understandable syntax that go already offers and more.
It works like any other language generics.

Lets assume this piece of code.


package main

import (
    "fmt"
)

func Writer[T string | int](w T) {
    fmt.Println(w)
}
func main() {
    Writer[int]("Hello")
    Writer(1)
}
Enter fullscreen mode Exit fullscreen mode

This code, as you may have guessed returns an error.

 cannot use "Hello" (untyped string constant) as int value in argument to Writer[int]
Enter fullscreen mode Exit fullscreen mode

To fix it, either we'd have to change the generic type to "string" or change the param of the function to int type.

package main

import (
    "fmt"
)

func Writer[T string | int](w T) {
    fmt.Println(w)
}
func main() {
    Writer[string]("Hello")
    Writer[int](1) 
}
Enter fullscreen mode Exit fullscreen mode

Notes

  • Golang hasnt yet announced a stable version, therefore it is not adviced to use it in production.
  • Due to addition of generics go 1.18-beta is roughly 15% slower check out more information about it here

Upgrading Version

Due to go 1.18 being unstable, golang has made the version a seperate executable.
You can download it here
and use

go1.18beta1 
Enter fullscreen mode Exit fullscreen mode

in the cli to check out the help menu.

OR

Install go1.18beta using the go cli (if you already have it installed)

go install golang.org/dl/go1.18beta1@latest
Enter fullscreen mode Exit fullscreen mode

and then use

go1.18beta1
Enter fullscreen mode Exit fullscreen mode

instead of

go
Enter fullscreen mode Exit fullscreen mode

Fyi, go does not update it just installs a seperate executable for testing out the beta version

Well have fun looking at the new features, until next time 🤠

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay