【发布时间】:2021-04-11 12:37:09
【问题描述】:
假设我有以下类型。
type Contract struct {
Id string `json:"id" gorm:"column:uuid"`
Name string `json:"name" gorm:"column:name"`
Description string `json:"descr" gorm:"column:descr"`
ContractTypeId int `json:"contract_type_id" gorm:"column:contract_type_id"`
}
type ContractModel struct {
Id string `json:"id" gorm:"column:uuid"`
Name string `json:"name" gorm:"column:name"`
Description string `json:"descr" gorm:"column:descr"`
}
我有一个 SQL 查询,使用 gorm 将结果扫描到合同对象中。
如何将合约对象的值映射到 contractModel 对象?
我尝试使用 go-automapper 这样的包:
automapper.Map(contract, ContractModel{})
我想删除ContractTypeId。
我可以对列表中的多种类型执行此操作吗?
var contractModels []ContractModel
automapper.Map(contracts, &contractModels)
【问题讨论】:
-
“我想删除
ContractTypeId。” -- 如果“删除”是指未设置,则可以使用contract.ContractTypeId = 0。如果“删除”是指完全“删除”该字段,那么这是不可能的,Go 中的类型是静态的,因此您不能在运行时从Contract添加或删除字段。 -
如果您想要将字段值从
contract复制到ContractModel类型的实例,这将自动省略ContractTypeId,因为ContractModel中不存在该字段,那么您有首先分配一个实例,然后将指向它的指针作为dest参数传递给autmapper.Map。例如var cm ContractModel;automapper.Map(contract, &cm);fmt.Println(cm). -
@mkopriva,这完全有道理并且对我有用。非常感谢。另一个问题,如果我有
contracts的列表,我可以做类似编辑的事情吗? -
您必须迭代切片并将每个项目单独复制到新类型并将其添加到新列表中。您可以预先分配新切片的大小以加快速度:
newSlice := make([]ContractModel, 0, len(oldSlice))。然后使用append追加项目。 -
@sgerbhctim AFAICT 查看source,是的,您应该能够在编辑中执行类似的操作。你试过了吗?
标签: go automapper go-gin