英文:
Golang type assertion issue
问题
我正在尝试调用这个 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) <<<<<<<<< 这里出错了
我的 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
}
我一直收到这个错误信息:
interface conversion: interface is *entities.ClassType, not 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
我做错了什么?
英文:
I am trying to call this Gorp function http://godoc.org/github.com/coopernurse/gorp#DbMap.Get
I am doing this:
// ClassType
obj, err := c.Gorp.Get(entities.ClassType{}, class.ClassTypeCode)
if err != nil {
panic(err)
}
class.ClassType = obj.(*entities.ClassType) <<<<<<<<< Error here
My Class looks like this:
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
}
I keep getting this error message:
interface conversion: interface is *entities.ClassType, not entities.ClassType
If I change my code to :
// ClassType
obj, err := c.Gorp.Get(entities.ClassType{}, class.ClassTypeCode)
if err != nil {
panic(err)
}
class.ClassType = obj.(*entities.ClassType)
I then get this message:
cannot use obj.(*entities.ClassType) (type *entities.ClassType) as type entities.ClassType in assignment
What am I doing wrong?
答案1
得分: 2
class.ClassType = *obj.(*entities.ClassType) 的翻译结果是:类.ClassType = *obj.(*entities.ClassType)
英文:
class.ClassType = *obj.(*entities.ClassType)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论