Rudziankoŭ
Rudziankoŭ

Reputation: 11251

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?

Upvotes: 5

Views: 4871

Answers (2)

Pavlo Strokov
Pavlo Strokov

Reputation: 2087

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

Upvotes: 4

Thundercat
Thundercat

Reputation: 121119

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:

Upvotes: 12

Related Questions