Help to understand code from flag package

I am learning go. First time I use one of the standard packages I try to read through it’s code to learn more about the package. I also Want to get a feel for how go code is written. This particular example is from the flag package.

Would someone be able to explain it to me? I just can’t wrap my head around it:

// isZeroValue determines whether the string represents the zero
// value for a flag.
func isZeroValue(flag *Flag, value string) bool {
	// Build a zero value of the flag's Value type, and see if the
	// result of calling its String method equals the value passed in.
	// This works unless the Value type is itself an interface type.
	typ := reflect.TypeOf(flag.Value)
	var z reflect.Value
	if typ.Kind() == reflect.Ptr {
		z = reflect.New(typ.Elem())
	} else {
		z = reflect.Zero(typ)
	}
	return value == z.Interface().(Value).String()
}

I know reflection from Java and I do understand the purpose of this function but can’t understand how it accomplishes that.
The last line of the method is totally nonsensical to me:)

Thanks in advance

Hi

Hard for me too. But it compares the value to

z.Interface() gets the zero-type as an interface{} it is then converted into an flag.Value type and then the string representation of that. But why not just do z.(Value).String() ???

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.