不可能的类型开关案例:不能有动态类型

时间:2018-02-24 20:20:34

标签: go interface switch-statement

有以下结构:

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
}

它的界面:

package dto

type Responder interface {
    Read() (interface{})
    GetError() (error)
    SetError(error)
    GetTransactionId() (string)
}

遵循逻辑:

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()))
                    }

                }
            }
        }
    }()
}

我得到例外:

impossible type switch case: r (type dto.Responder) cannot have dynamic type dto.CapacityResponse (missing GetError method)

请你帮我理解这里有什么问题?

0 个答案:

没有答案