如何使用 reflect.DeepEqual() 来将指针的值与其类型的零值进行比较?

huangapple go评论81阅读模式
英文:

How do I use reflect.DeepEqual() to compare a pointer's value against the zero value of its type?

问题

我需要一个通用函数来检查某个值是否等于其零值。

从这个问题中,我找到了一个适用于值类型的函数。我修改了它以支持指针:

func isZeroOfUnderlyingType(x interface{}) bool {

	rawType := reflect.TypeOf(x)

	// 如果是指针,转换为其值
	if rawType.Kind() == reflect.Ptr {
		rawType = rawType.Elem()
	}

	return reflect.DeepEqual(x, reflect.Zero(rawType).Interface())
}

不幸的是,当我像这样做时,它对我不起作用:

type myStruct struct{}

isZeroOfUnderlyingType(myStruct{}) // 返回 true(有效)

isZeroOfUnderlyingType(&myStruct{}) // 返回 false(无效)

这是因为&myStruct{}是一个指针,在函数内部无法解引用interface{}。我该如何将该指针的值与其类型的零值进行比较?

英文:

I need a generic function to check whether something is equal to its zero-value or not.

From this question, I was able to find a function that worked with value types. I modified it to support pointers:

func isZeroOfUnderlyingType(x interface{}) bool {

	rawType := reflect.TypeOf(x)

	//source is a pointer, convert to its value
	if rawType.Kind() == reflect.Ptr {
		rawType = rawType.Elem()
	}

	return reflect.DeepEqual(x, reflect.Zero(rawType).Interface())
}

Unfotunately, this didn't work for me when doing something like this:

type myStruct struct{}

isZeroOfUnderlyingType(myStruct{}) //Returns true (works)

isZeroOfUnderlyingType(&myStruct{}) //Returns false (doesn't) work

This is because &myStruct{} is a pointer and there is no way to dereference an interface{} inside the function. How do I compare the value of that pointer against the zero-value of its type?

答案1

得分: 4

reflect.Zero() 返回一个 reflect.Valuereflect.New() 返回一个指向零值的指针。

我更新了这个函数,以检查 x 是指向某个东西的指针的情况:

func isZeroOfUnderlyingType(x interface{}) bool {

    rawType := reflect.TypeOf(x)

    if rawType.Kind() == reflect.Ptr {
        rawType = rawType.Elem()
        return reflect.DeepEqual(x, reflect.New(rawType).Interface())
    }

    return reflect.DeepEqual(x, reflect.Zero(rawType).Interface())
}
英文:

reflect.Zero() returns a reflect.Value. reflect.New() returns a pointer to a zero value.

I updated the function to check the case where x is a pointer to something:

func isZeroOfUnderlyingType(x interface{}) bool {

    rawType := reflect.TypeOf(x)

    if rawType.Kind() == reflect.Ptr {
        rawType = rawType.Elem()
        return reflect.DeepEqual(x, reflect.New(rawType).Interface())
    }

    return reflect.DeepEqual(x, reflect.Zero(rawType).Interface())
}

huangapple
  • 本文由 发表于 2017年1月20日 12:45:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/41756279.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定