Mapping one type to another

帅比萌擦擦* 提交于 2021-01-07 01:36:17

问题


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

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

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

I tried using the package go-automapper as such:

automapper.Map(contract, ContractModel{})

I want to drop the ContractTypeId.

Can I do this for multiple types in a list?

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

回答1:


Assign the fields individually.

v := ContractModel{
    Id:          contract.Id,
    Name:        congtract.Name,
    Description: contact.Description,
}



回答2:


You can do either:

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

Or call automapper.Map in a loop:

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

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.



来源:https://stackoverflow.com/questions/65584357/mapping-one-type-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!