Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

impossible type switch case: cannot have dynamic type

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?

like image 615
Rudziankoŭ Avatar asked Feb 24 '18 20:02

Rudziankoŭ


2 Answers

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:
like image 161
Bayta Darell Avatar answered Sep 28 '22 17:09

Bayta Darell


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

like image 34
Pavlo Strokov Avatar answered Sep 28 '22 19:09

Pavlo Strokov