Golang类型断言问题

时间:2014-01-22 21:09:46

标签: go

我试图称之为Gorp函数http://godoc.org/github.com/coopernurse/gorp#DbMap.Get

我这样做:

       // ClassType
    obj, err := c.Gorp.Get(entities.ClassType{}, class.ClassTypeCode)
    if err != nil {
        panic(err)
    }
    class.ClassType = obj.(*entities.ClassType)  <<<<<<<<< Error here

My Class看起来像这样:

package entities

import (
    "time"
)

type Class struct {
    Id                int
    ClassTypeCode     string
    VideoPath         string
    VideoSize         int
    Duration          float64
    CreatedAt         time.Time
    VisibleAt         time.Time
    NoLongerVisibleAt time.Time

    // Relationships
    ClassType  ClassType
    Instructor User
    Equipment  []Equipment
}

我不断收到此错误消息: 接口转换:接口是* entities.ClassType,而不是entities.ClassType

如果我将代码更改为:

            // ClassType
    obj, err := c.Gorp.Get(entities.ClassType{}, class.ClassTypeCode)
    if err != nil {
        panic(err)
    }
    class.ClassType = obj.(*entities.ClassType)

然后我收到这条消息:

cannot use obj.(*entities.ClassType) (type *entities.ClassType) as type entities.ClassType in assignment

我做错了什么?

1 个答案:

答案 0 :(得分:2)

class.ClassType = *obj.(*entities.ClassType)