sectasy
sectasy

Reputation: 98

Use struct as wrapper in go

How to wrap redis.Client to my struct? I have that code and gives me an error

package main

import (
    "github.com/go-redis/redis"
)

var cache *RedisCache

// RedisCache struct
type RedisCache struct {
    *redis.Client
}

func initCache() *RedisCache {
    if cache == nil {
        cache = redis.NewClient(&redis.Options{
           Addr:     "localhost:6379",
            Password: "",
            DB:       0,
        })
    }

    return cache
}
cannot use redis.NewClient(&redis.Options literal) (type *redis.Client) as type *RedisCache in assignment

There is some method to convert that property?

Upvotes: 0

Views: 1062

Answers (1)

icza
icza

Reputation: 418435

redis.NewClient() returns a value of type *redis.Client. Use a composite literal to create a value of your RedisCache which you can assign to cache:

func initCache() *RedisCache {
    if cache == nil {
        client := redis.NewClient(&redis.Options{
            Addr:     "localhost:6379",
            Password: "",
            DB:       0,
        })
        cache = &RedisCache{Client: client}
    }

    return cache
}

Upvotes: 4

Related Questions