Example of how Golang generics minimize the amount of code you need to write
3 min read Go Programming

Example of how Golang generics minimize the amount of code you need to write

I guess that almost everyone in the go community was exciting when Go 1.18 was released, especially because of generics. Some days ago I decided to try generics in the real-world application, by refactoring some of its pieces, related to a caching logic.

In our web application, we have multiple resolvers that execute some sql queries and return data in different types. Obviously, we want to prevent the database overloading by caching the same responses.


    // MyExampleType1 type to serve example response 1.
    type MyExampleType1 struct {}
    // MyExampleType2 type to serve example response 2.
    type MyExampleType2 struct {}

    // MyCachedResolver1 checks if there are any cached data by specific key.
    // If nothing in cache, queries the database and adds result to the redis cache.
    func MyCachedResolver1(redisClient *redis.Client) ([]MyExampleType1, error) {
      key := "resolver_result"
	  value, found := redisClient.Get(ctx, key)
	  if !found {
		value, err := FetchSomethingHeavyFromDB()
		if err != nil {
			return nil, err
		}

		valueJson, err := json.Marshal(value)
		if err != nil {
			return nil, err
		}
		redisClient.Set(context.Background(), key, valueJson, time.Hour*12)
		return value, nil
	  }

	  var val []MyExampleType1
	  err := json.Unmarshal([]byte(value.(string)), &val)
	  if err != nil {
		return nil, err
	  }
	  return val, nil
    }

    // MyCachedResolver2 checks if there are any cached data by specific key.
    // If nothing in cache, queries the database and adds result to the redis cache.
    func MyCachedResolver2(redisClient *redis.Client) ([]MyExampleType2, error) {
      key := "resolver_result_2"
	  value, found := redisClient.Get(ctx, key)
	  if !found {
		value, err := FetchSomethingEvenMoreHeavierFromDB()
		if err != nil {
			return nil, err
		}

		valueJson, err := json.Marshal(value)
		if err != nil {
			return nil, err
		}
		redisClient.Set(context.Background(), key, valueJson, time.Hour*12)
		return value, nil
	  }

	  var val []MyExampleType2
	  err := json.Unmarshal([]byte(value.(string)), &val)
	  if err != nil {
		return nil, err
	  }
	  return val, nil
    }

As you can see, there is some repetitive code that should be written due to the different types MyExampleType1 and MyExampleType2.

Now, let’s see how we can improve this situation by using generics. I’m going to write a function WithCache() which will be responsible for setting and getting data to/from redis cache.

    // WithCache adds exec function result into the redis cache.
    // Pay attention to "T any" that allows us to pass any type to this function.
    func WithCache[T any](redisClient *redis.Client, ctx context.Context, key string, exec func() (T, error), ttl time.Duration) (T, error) {
    	value, found := redisClient.Get(ctx, key)
    	var result T
    	if !found {
            // exec() is a function that should be executed to fetch needed data.
    		value, err := exec()
    		if err != nil {
    			return result, err
    		}
    		jsonValue, err := json.Marshal(value)
    		if err != nil {
    			return result, err
    		}
    		redisClient.Set(ctx, key, jsonValue, ttl)
    		return value, nil
    	}
    	var val T
    	err := json.Unmarshal([]byte(value.(string)), &val)
    	if err != nil {
    		return result, err
    	}
    	return val, nil
    }

After that our resolvers could be refactored into this:

     func MyCachedResolver1(redisClient *redis.Client) ([]MyExampleType1, error) {
       key := "resolver_result_1"
       return WithCache[[]MyExampleType1](redisClient, context.Background(), key, func() ([]MyExampleType1, error) {
		 return FetchSomethingHeavyFromDB()
	   }, time.Hour*12)
     }

     func MyCachedResolver2(redisClient *redis.Client) ([]MyExampleType2, error) {
       key := "resolver_result_2"
       return WithCache[[]MyExampleType2](redisClient, context.Background(), key, func() ([]MyExampleType2, error) {
		 return FetchSomethingEvenMoreHeavierFromDB()
	   }, time.Hour*12)
     }

Now it looks much better and clearer!

A

Alex

Passionate about web development and sharing knowledge with the community.

Share on X

You might also like