Skip to content

Goの仕様として関数同士の比較はできない

Goの言語仕様では、関数は nil との比較だけ行える。Goで関数が同一かどうか調べるための保証された方法は存在しない。

Goの言語仕様には次のような記述がある。

Slice, map, and function types are not comparable. However, as a special case, a slice, map, or function value may be compared to the predeclared identifier nil.

また、reflect.Value.Pointerのドキュメントにも保証しないと書いてある。

If v’s Kind is Func, the returned pointer is an underlying code pointer, but not necessarily enough to identify a single function uniquely. The only guarantee is that the result is zero if and only if v is a nil func Value.

関数へのポインタを含む構造体を reflect.DeepEqual すると常に false を返す。

package main
import (
"fmt"
"reflect"
)
type S struct {
N int
F func()
}
func main() {
s := S{30, main}
fmt.Println(reflect.DeepEqual(s, s)) // false
}