将一种类型映射到另一种类型

将一种类型映射到另一种类型

问题描述:

假设我有以下几种类型.

Let's say I have the following types.

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"`
}

我有一个使用 gorm 将结果扫描到合同对象中的SQL查询.

I have a SQL query using gorm to scan results into a contract object.

如何将合约对象中的值映射到contractModel对象中?

How can I map the values from the contract object into contractModel object?

我尝试使用软件包 go-automapper 如此:

I tried using the package go-automapper as such:

automapper.Map(contract, ContractModel{})

我要删除 ContractTypeId .

我可以对列表中的多种类型执行此操作吗?

Can I do this for multiple types in a list?

var contractModels []ContractModel
automapper.Map(contracts, &contractModels)

您可以执行以下任一操作:

You can do either:

models := []ContractModel{}
automapper.Map(contracts, &models)

或循环调用 automapper.Map :

models := make([]ContractModel, len(contracts))
for i := range contracts {
    automapper.Map(contracts[i], &models[i])
}

您应该知道,自动映射器在后台使用反射,因此比@ThinkGoodly建议的直接非多态复制要慢得多.如果性能不是头等大事,那将是一个很好的解决方案.

You should be aware that automapper uses reflection behind the scenes and thus is much slower than straight forward non-polymorphic copying like @ThinkGoodly suggests. It's a totally fine solution if performance isn't top priority though.