douyan4958 2017-01-06 13:26
浏览 244
已采纳

如何解决通过interface {}传递对象是否没有初始化字段

I have problem with resolve whether object which was pass as interface to function hasn't initializated fields, like object which was defined as just someObject{} is a empty, because all fields, has value 0, or nil

Problem becomes more complicated if I pass diffrent objects, because each object have diffrent type field value so on this moment I don't find universal way to this.

Example

func main(){
    oo := objectOne{}
    ot := objectTwo{}
    oth := objectThree{"blah" , "balbal" , "blaal"}
    resolveIsNotIntialized(oo)
    resolveIsNotIntialized(ot)
    resolveIsNotIntialized(oth)
}

func resolveIsNotIntialized(v interface{}) bool{
    // and below, how resolve that oo and ot is empty
    if (v.SomeMethodWhichCanResolveThatAllFiledIsNotIntialized){
        return true
    }
    return false
}

I want to avoid usage switch statement like below, and additional function for each object, ofcorse if is possible.

func unsmartMethod(v interface{}) bool{
    switch v.(type){
    case objectOne:
        if v == (objectOne{}) {
          return true
        }
        // and next object, and next....
    }
    return false
}
  • 写回答

3条回答 默认 最新

  • duanjia4969 2017-01-06 14:08
    关注

    As Franck notes, this is likely a bad idea. Every value is always initialized in Go. Your actual question is whether the type equals its Zero value. Generally the Zero value should be designed such that it is valid. The better approach would generally be to create an interface along the lines of:

    type ZeroChecker interface {
        IsZero() bool
    }
    

    And then attach that to whatever types you want to check. (Or possibly better: create an IsValid() test instead rather than doing your logic backwards.)

    That said, it is possible to check this with reflection, by comparing it to its Zero.

    func resolveIsNotIntialized(v interface{}) bool {
        t := reflect.TypeOf(v)
        z := reflect.Zero(t).Interface()
        return reflect.DeepEqual(v, z)
    }
    

    (You might be able to get away with return v == z here; I haven't thought through all the possible cases.)

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

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀