Have following struct:
package dto
type CapacityResponse struct{
Val int
Err error
TransactionID string
}
func (r *CapacityResponse) GetError() (error) {
return r.Err
}
func (r *CapacityResponse) SetError(err error) {
r.Err = err
}
func (r *CapacityResponse) Read() interface{} {
return r.Val
}
func (r *CapacityResponse) GetTransactionId() string {
return r.TransactionID
}
It's interface:
package dto
type Responder interface {
Read() (interface{})
GetError() (error)
SetError(error)
GetTransactionId() (string)
}
And following logic:
func handler(w http.ResponseWriter, r *http.Request) {
cr := request2CacheRequest(r)
responseChan := make(chan dto.Responder)
go func() {
responder := processReq(cr)
responseChan <- responder
}()
go func() {
for r := range responseChan {
if (r.GetTransactionId() == cr.TransactionID) {
switch r.(type) {
//case dto.KeysResponse:
//case dto.GetResponse:
//case dto.RemoveResponse:
//case dto.SetResponse:
case dto.CapacityResponse:
if i, ok := r.Read().(int); ok {
fmt.Fprintf(w, fmt.Sprintf("{'capasity': %d, 'err': %s}", i, r.GetError()))
}
}
}
}
}()
}
I am getting exception:
impossible type switch case: r (type dto.Responder) cannot have dynamic type dto.CapacityResponse (missing GetError method)
Could you, please, help me to understand what is wrong here?
The error message is saying that a dto.Responder value cannot contain a dto.CapacityResponse because dto.CapacityResponse is missing one of the dto.Responder methods (GetError).
The pointer type implements the interface. Change the case to:
case *dto.CapacityResponse:
You have this error because dto.CapacityResponse
type is different from *dto.CapacityResponse
type.
Because you are using local variable r
of interface type dto.Responder
the only concrete types you can use in case
statements are those that implement this interface and dto.CapacityResponse
isn't one of them, because it is not a pointer type and you have declared receivers as pointers for dto.CapacityResponse
. Please take a look on playground example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With