Home > Backend Development > Golang > How Can I Reliably Compare Function Pointers for Equality in Go?

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

Linda Hamilton
Release: 2024-12-18 09:35:11
Original
234 people have browsed it

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
}
Copy after login

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

The above is the detailed content of How Can I Reliably Compare Function Pointers for Equality in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template