【问题标题】:Compile error on type comparison类型比较的编译错误
【发布时间】:2016-08-17 18:47:43
【问题描述】:

我得到如下所示的编译错误,说 ErrFieldMismatch 类型缺少 Error() 方法,但如最后一个代码块所示,它不是。

知道为什么我不能为此执行类型比较吗?

错误

impossible type switch case: err (type error) cannot have dynamic type "google.golang.org/appengine/datastore".ErrFieldMismatch (missing Error method)

我的代码

type Program struct {
    aemodel.Base

    Name        string   `json:"name" required:"true"`
    Public      bool     `json:"isPublic"`
    Description string   `json:"description" required:"true"`
    Default     bool     `json:"isDefault"`
    Tags        []string `json:"tags"`

    // Level int
}

// Load - PropertyLoadSaver interface
func (p *Program) Load(ps []datastore.Property) error {
    if err := datastore.LoadStruct(p, ps); err != nil {
        switch err.(type) {
        case datastore.ErrFieldMismatch:  // <-- Failure point
            return nil
        default:
            return err
        }
    }
    return nil
}

应用引擎代码

type ErrFieldMismatch struct {
    StructType reflect.Type
    FieldName  string
    Reason     string
}

func (e *ErrFieldMismatch) Error() string {
    return fmt.Sprintf("datastore: cannot load field %q into a %q: %s",
        e.FieldName, e.StructType, e.Reason)
}

【问题讨论】:

    标签: google-app-engine go


    【解决方案1】:

    Error 方法定义在指向datastore.ErrFieldMismatch 的指针类型上,即Error 定义在*datastore.ErrFieldMismatch 上,因此只有*datastore.ErrFieldMismatch 实现了Error 接口。

    尝试更改您的 case 表达式:

    func (p *Program) Load(ps []datastore.Property) error {
        if err := datastore.LoadStruct(p, ps); err != nil {
            switch err.(type) {
            case *datastore.ErrFieldMismatch:  // use pointer type here
                return nil
            default:
                return err
            }
        }
        return nil
    }
    

    【讨论】:

    • 感谢您的帮助:)
    猜你喜欢
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    • 2014-12-09
    • 2011-05-28
    • 1970-01-01
    • 2013-08-16
    相关资源
    最近更新 更多