将一种类型映射到另一种类型 [英] Mapping one type to another

查看:99
本文介绍了将一种类型映射到另一种类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下几种类型.

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.

这篇关于将一种类型映射到另一种类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆