DEV Community

omoogun olawale
omoogun olawale

Posted on

2

Golang: Generics in Go

Hi devs,
I will be writing an interesting article on how generics helped me solve a challenging problem while I was working on a simple REST API project built with GoLang using the gin framework.

The problem

/* model.go */
type LoginAuth struct {
    USERNAME string `bson:"username" json:"username" validate:"required,min=1"`
    PASSWORD string `bson:"username" json:"password" validate:"required,min=4"`
}

/* controller.go */
var user model.LoginAuth
if err := c.BindJSON(&user); err != nil {
  c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  return
}
Enter fullscreen mode Exit fullscreen mode

The code snippet above is from an authentication controller.
My goal is to reuse this code snippet below with other resources's controllers with different types.

e.g Comment controller with model.Comment type

var user model.LoginAuth
if err := c.BindJSON(&user); err != nil {
  c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  return
}
Enter fullscreen mode Exit fullscreen mode

The Solution

func bindJSONData[T any](c *gin.Context) (T, bool) {
    var data T
    if err := c.BindJSON(&data); err != nil {
        utils.AbortResponse(c, utils.Reponse{StatusCode: http.StatusUnprocessableEntity, Success: false, Message: err.Error(), Data: nil})
        return *new(T), false
    }
    return data, true
}
Enter fullscreen mode Exit fullscreen mode
  • I created a generic function bindJSONData that takes a type parameter T.
  • This T represents the struct type we want to bind the JSON data to.
  • Inside the function, I declared a variable data of type T.
  • The c.BindJSON(&data) call remains the same, but now it dynamically binds to the type specified by T.
  • The function now returns both the bound data of type T and a boolean indicating success. This makes the calling code cleaner.
  • If binding fails, it returns the zero value of type T and false.

Hope this post helps. Feel free to leave a comment on this post I will be in the comment section.

DevCycle image

Fast, Flexible Releases with OpenFeature Built-in

Ship faster on the first feature management platform with OpenFeature built-in to all of our open source SDKs.

Start shipping

Top comments (0)

AWS Q Developer image

Build your favorite retro game with Amazon Q Developer CLI in the Challenge & win a T-shirt!

Feeling nostalgic? Build Games Challenge is your chance to recreate your favorite retro arcade style game using Amazon Q Developer’s agentic coding experience in the command line interface, Q Developer CLI.

Participate Now

👋 Kindness is contagious

Explore this compelling article, highly praised by the collaborative DEV Community. All developers, whether just starting out or already experienced, are invited to share insights and grow our collective expertise.

A quick “thank you” can lift someone’s spirits—drop your kudos in the comments!

On DEV, sharing experiences sparks innovation and strengthens our connections. If this post resonated with you, a brief note of appreciation goes a long way.

Get Started