1

Here is my code:

type ICacheEngine interface {
   // ...
}

// implements all methods of ICacheEngine
type RedisCache struct { }

type ApplicationCache struct { 
  Cache *ICacheEngine
}

func NewRedisCache() *ApplicationCache {
    appCache := new(ApplicationCache)
    redisCache := new(RedisCache)
    appCache.Cache = redisCache   // here is an error : can not use *RedisCache as *ICacheEngine
    return appCache
}

RedisCache implements all methods of ICacheEngine. I can pass RedisCache to the method which get ICacheEngine:

func test(something ICacheEngine) *ICacheEngine {
    return &something
}

....

appCache.Cache = test(redisCache)

But I cannot assign RedisCache to ICacheEngine. Why ? How can I avoid test() function ? And what will be looking programming with interfaces when I set concrete type to interface and next call it methods ?

ceth
  • 44,198
  • 62
  • 180
  • 289
  • First you are able to assign `redisCache` to `ICacheEngine` Because it is an interface. You can pass any type of argument to a function with interface parameter. – Himanshu Jun 28 '18 at 05:05
  • 2
    Two comments: Never use a pointer to an interface (this is _wrong_ in almost all the cases). Do not call an interface `I...` (this is neither C# nor Java). – Volker Jun 28 '18 at 05:22

2 Answers2

6

Considering an interface can store a stuct or a pointer to a struct, make sure to define your ApplicationCache struct as:

type ApplicationCache struct { 
  Cache ICacheEngine
}

See "Cast a struct pointer to interface pointer in Golang".

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
0

Here clientStruct is implementing the "ClientInterface".

And we assigning the struct to interface.

package restclient

import (
    "net/http"
)

type clientStruct struct{}

type ClientInterface interface {
    Get(string) (*http.Response, error)
}
// assigning the struct to interface
var (
    ClientStruct ClientInterface = &clientStruct{}
)

func (ci *clientStruct) Get(url string) (*http.Response, error) {
    request, err := http.NewRequest(http.MethodGet, url, nil)
    if err != nil {
        return nil, err
    }
    client := http.Client{}

    return client.Do(request)
}
Siyaram Malav
  • 4,414
  • 2
  • 31
  • 31