Golang 与 GORM。如何正确地将模型类型传递到方法中?
时间:2024-04-07
浏览:349
作者:佚名
从现在开始,我们要努力学习啦!今天我给大家带来《Golang 与 GORM。如何正确地将模型类型传递到方法中?》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!
问题内容
我有下一个 gorm 模型
package entity
import (
"github.com/jinzhu/gorm"
)
type interfaceentity interface {
}
type user struct {
interfaceentity
gorm.model
name string
}
我尝试将 gorm 实体类型传递到基本 crud 存储库中。我的基本 crud 存储库:
package repository
import (
"billingo/model/entity"
"fmt"
"github.com/jinzhu/gorm"
"reflect"
)
type crudrepository struct {
*baserepository
}
func newcrudrepository(db *gorm.db) crudrepositoryinterface {
repo := newbaserepository(db).(*baserepository)
return &crudrepository{repo}
}
func (c crudrepository) find(id uint, item entity.interfaceentity) entity.interfaceentity {
fmt.println("--- initial")
var local entity.user
fmt.println("--- local: ", reflect.typeof(local), local)
fmt.println("--- item: ", reflect.typeof(item), item)
fmt.println("--- values")
c.db.first(&local, id)
fmt.println("--- local: ", reflect.typeof(local), local)
c.db.first(&item, id)
fmt.println("--- item: ", reflect.typeof(item), item)
return item
}
如您所见,find() 方法中的 item 和 local 变量。
我使用服务中的下一种方式传递 item:
func (c crudservice) getitem(id uint) entity.interfaceentity {
var item entity.user
return c.repository.find(id, item)
}
看来 local 和 item 必须相等,并且行为必须等效。
但是输出是
--- Initial
--- local: entity.User {<nil> {0 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC <nil>} }
--- Item: entity.User {<nil> {0 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC <nil>} }
--- Values
--- local: entity.User {<nil> {1 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC <nil>} test 1}
--- Item: entity.User {<nil> {0 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC <nil>} }
INFO[0000] User info user="{<nil> {0 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC <nil>} }" user-id=1
(/home/mnv/go/src/billingo/model/repository/CrudRepository.go:29)
[2019-05-17 17:07:37] unsupported destination, should be slice or struct
item 从服务传递到消息
不支持的目标,应该是切片或结构
如何正确传递 item,我需要像 local 那样的行为?
解决方案
哦,我已经解决了。
现在使用 &item 从服务调用存储库方法 find:
func (c crudservice) getitem(id uint) entity.interfaceentity {
var item entity.user
return c.repository.find(id, &item)
}
存储库方法传递 item 而不带 &:
func (c CrudRepository) Find(id uint, item entity.InterfaceEntity) entity.InterfaceEntity {
c.db.First(item, id)
return item
}
gorm 不想将数据解组到您的空接口类型中。
即使您传入一个实现该特定接口的结构,它在传递后仍然保持为接口的类型。您需要将该 item 接口强制转换回 user 结构。
喜欢 item.(entity.user)
今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.26
11.26
11.26
11.26
11.26
热门专题
