Golang类型断言问题

huangapple go评论75阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2014年1月23日 05:09:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/21294049.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定