Home > Backend Development > Golang > How Can I Safely Compare Function Pointers for Identity in Go?

How Can I Safely Compare Function Pointers for Identity in Go?

Linda Hamilton
Release: 2024-12-26 17:55:09
Original
695 people have browsed it

How Can I Safely Compare Function Pointers for Identity in Go?

Function Pointer Equality in Go

In Go, comparing function pointers for equality using == or != operators is not allowed for functions that are not nil. This behavior prevents the mixing of equality and identity comparisons.

Function equality differs from function identity. Identity comparisons should be used to determine if two functions are the same function, while equality comparisons should be used to determine if two functions are equivalent.

Using the reflect package to compare function identity, as shown in the Atom example, is considered undefined behavior. The compiler may optimize functions by merging their implementations, making the comparison unreliable.

To correctly compare function pointers for identity, you can create unique variables for each function and then compare the addresses of those variables. This approach ensures that you are comparing function pointers for the same function, regardless of optimizations.

Here is an example of how to compare function pointers for identity:

package main

import "fmt"

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

var F1_ID = F1  // Create a *unique* variable for F1
var F2_ID = F2  // Create a *unique* variable for 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

The above is the detailed content of How Can I Safely Compare Function Pointers for Identity 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