golang nil interface convert to basic type panic

忍不住吐槽下资深c++工程师转go两年后写的代码

conf := RedisConf {
    Name: name,
    Addr: addrs,
    Password: item["password"].(string),
    Namespace: item["namespace"].(string),
    Retries: int(item["retries"].(float64)),
    ReadTimeout: int(item["read_timeout"].(float64)),
    WriteTimeout: int(item["write_timeout"].(float64)),
    PoolSize: int(item["pool_size"].(float64)),
}

  如果你一眼看出问题那么恭喜你

上面的代码从map取值后直接转换类型的形式可能发生panic ,而且没有加任何defer recover, 如果我来写的话可能是这样 

        conf := RedisConf{
            Name: name,
            Addr: addrs,
        }

        conf.Password, _ = item["password"].(string)
        conf.Namespace, _ = item["namespace"].(string)
        conf.Retries, _ = item["retries"].(int)
        conf.ReadTimeout, _ = item["read_timeout"].(int)
        conf.WriteTimeout, _ = item["write_timeout"].(int)
        conf.PoolSize, _ = item["pool_size"].(int)

这样其实可以解决一大部分问题,

最好的方式其实是对结构体字段进行初始化赋值,这样就算配置没有赋值也不会报错。

  

posted on 2021-12-01 17:44  iokde.com  阅读(29)  评论(0编辑  收藏  举报

导航