douhao2548 2015-07-16 18:19
浏览 3
已采纳

改进多图访问,避免错误的类型转换

I have this code in my project:

//data.Objects is a map[string]interface{}
corporateName := data.Objects["corporateName"].(string)
dba := data.Objects["dba"].(string)
licence := data.Objects["licence"].(string)
resaleCert := data.Objects["resaleCert"].(string)
einNumber := data.Objects["einNumber"].(string)
phoneNumber := data.Objects["phoneNumber"].(string)
website := data.Objects["website"].(string)
contactName := data.Objects["contactName"].(string)
email := data.Objects["email"].(string)
billingAddress := data.Objects["billingStreet"].(string)
billingCity := data.Objects["billingCity"].(string)
billingCode := data.Objects["billingCode"].(int64)
billingState := data.Objects["billingState"].(string)
billingCountry := data.Objects["billingContry"].(string)
deliveryAddress := data.Objects["deliveryAddress"].(string)

In the declared map, some of these key couldn't have a value associated so they can return nil. If they do that I'm not able to do a type conversion. I'm looking for a way in order to improve this access and prevent the incorrect conversion.

Using some if else to check it it's quite annoying and verbose. Is there a way in order to avoid it?

N.B. The nil values for the structure are perfectly legal in this case so it's not a problem that I can avoid before.

  • 写回答

2条回答 默认 最新

  • dongliang1941 2015-07-16 19:51
    关注

    As @JimB mentions you can use a custom type, e.g.

    type detailsMap map[string]interface{}
    
    func (dm detailsMap) String(key string) string {
        if val, ok := dm[key].(string); ok {
            return val
        }
        return ""
    }
    
    func (dm detailsMap) Int64(key string) int64 {
        if val, ok := dm[key].(int64); ok {
            return val
        }
        return 0
    }
    

    Note that default zero values are returned if the desired key is not present in the type's underlying map[string]interface{}.

    If you haven't got control of the original data.Objects then you can convert it to a detailsMap via detailsMap(data.Objects).

    You can then get values out as follows:

    corporateName := dm.String("corporateName")
    website := dm.String("website")
    billingCode := dm.Int64("billingCode")
    

    Here's an example on the playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果