Home > Article > Backend Development > How Can You Compare Functions in Go?
In Go, functions are first-class values, meaning they can be assigned to variables and passed around as arguments to other functions. However, unlike other types in Go, functions are not comparable by default. This can lead to confusion when attempting to compare functions in your code.
As detailed in the Go language specifications, function values are not comparable. Attempting to compare function values using standard comparison operators such as == or != will result in a compiler error.
<code class="go">if handler.Post != Undefined { // ... }</code>
The Undefined function present in the code sample is an example of a function that is not defined in the same way as regular functions. It is declared as a function that takes a single string argument and returns nothing (func Undefined(foo string)). Undefined is then assigned to the Get field of the Handler struct in the init function. This assignment creates a function value for Undefined that is stored in the Get field.
While functions themselves cannot be compared, it is possible to compare the addresses of function values. This can be achieved by using the fmt.Sprintf function to obtain the string representation of the function address and then comparing the resulting strings.
<code class="go">p1 := fmt.Sprintf("%v", Undefined) p2 := fmt.Sprintf("%v", hand.Get) fmt.Println("Expecting true:", p1 == p2)</code>
This method effectively converts the function values to strings, which can then be compared using the == operator.
An alternative approach to comparing function value addresses is to use the reflect.Value.Pointer() method. This method returns the memory address of the reflected value, which can then be compared to the address of another function value.
<code class="go">u1 := reflect.ValueOf(Undefined).Pointer() u2 := reflect.ValueOf(hand.Get).Pointer() fmt.Println("Expecting true:", u1 == u2)</code>
It is generally not recommended to compare function value addresses. Instead, refactoring your code to eliminate the need for such comparisons is a more efficient and maintainable approach. Consider using a different approach, such as defining an interface or using type assertion, to achieve your desired behavior.
The above is the detailed content of How Can You Compare Functions in Go?. For more information, please follow other related articles on the PHP Chinese website!