确认在Go中结构字段非零

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

Confirm struct fields non-zero in Go

问题

我正在尝试编写一个通用函数,该函数接受一个struct并确认给定的字段具有非零值。

这是我的函数:

func CheckRequiredFields(kind string, i interface{}, fields ...string) error {
    for _, field := range fields {
        value := reflect.ValueOf(i).FieldByName(field)
        if value.Interface() == reflect.Zero(value.Type()).Interface() {
            return fmt.Errorf("missing required %s field %s", kind, field)
        }
    }
    return nil
}

如果将struct作为i传入,它可以正常工作,但如果i是指向struct的指针,则会失败。

如果传入的值是指针,我该如何反射接口的值呢?

英文:

I am trying to write a generic function that takes a struct and confirms that the given fields have non-zero values.

This is my function:

func CheckRequiredFields(kind string, i interface{}, fields ...string) error {
	for _, field := range fields {
		value := reflect.ValueOf(i).FieldByName(field)
		if value.Interface() == reflect.Zero(value.Type()).Interface() {
			return fmt.Errorf("missing required %s field %s", kind, field)
		}
	}
	return nil
}

and it works well if a struct is passed in as i, but fails if i is a pointer to a struct.

How can I reflect on the value of an interface if the value passed in is a pointer?

答案1

得分: 1

你可以使用reflect.Indirect函数,它返回v指向的值。如果v是一个空指针,Indirect函数会返回一个零值。如果v不是指针,Indirect函数会返回v本身。

如果你想检查值是否为指针类型,可以使用Kind方法,并使用Elem()方法解引用指针。

v := reflect.ValueOf(i)
if v.Kind() == reflect.Ptr {
    v = v.Elem()
}
英文:

You can use reflect.Indirect, which returns the value that v points to. If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirect returns v.

If you want to check if the value was a pointer or not, check it's Kind, and use Elem() to dereference the pointer.

v := reflect.ValueOf(i)
if v.Kind() == reflect.Ptr {
    v = v.Elem()
}

huangapple
  • 本文由 发表于 2017年2月3日 22:09:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/42026159.html
匿名

发表评论

匿名网友

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

确定