"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Reliably Compare Function Pointers for Equality in Go?

How Can I Reliably Compare Function Pointers for Equality in Go?

Published on 2024-12-22
Browse:591

How Can I Reliably Compare Function Pointers for Equality in Go?

Detecting Pointer Equality for Functions in Go Weekly

Traditionally, comparing two non-nil function pointers in Go involved the use of == or != operators. However, following recent changes, this approach now results in errors.

The Rationale Behind the Change

The elimination of pointer equality comparison for functions stems from the concept of equality vs. identity. In Go, == and != operators assess equivalence for values, not identity. This distinction aims to prevent confusion between these concepts.

Performance Considerations

Additionally, comparisons of functions impact performance. For instance, anonymous closures that do not refer to external variables should be optimized into a single implementation by the compiler. Comparing function pointers would hinder this optimization, requiring dynamic creation of new closures at runtime.

Utilizing the Reflect Package

While it's possible to determine function identity using the reflect package, it's important to note that this approach entails undefined behavior. The results of such comparisons are unreliable, as the compiler may decide to collapse multiple functions into a single implementation.

A Valid Solution

To effectively compare function pointers, the following approach can be employed:

package main

import "fmt"

func F1() {}
func F2() {}

var F1_ID = F1 // Assign a unique variable to F1
var F2_ID = F2 // Assign a unique variable to F2

func main() {
    f1 := &F1_ID // Take the address of F1_ID
    f2 := &F2_ID // Take the address of F2_ID

    // Compare pointers
    fmt.Println(f1 == f1) // Prints true
    fmt.Println(f1 == f2) // Prints false
}

By employing pointers to unique variables associated with each function, you can effectively detect pointer equality among functions.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3