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

如何解决通过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条)

报告相同问题?