如何使两个对象具有可比性

时间:2017-03-09 20:32:19

标签: go

我将两个不同结构的对象传递给一个函数,并将其与保存为interface {}类型的现有对象进行比较。

在下文中,如何使两个对象与Equality ===

相媲美

在这次尝试中,与bar的比较工作正常,但是foo会抛出一个恐慌错误,尽管这两个对象都是结构类型

Go Playground

package main

import "fmt"

type Foo struct {
    TestMethod func(str string)
}

type Bar struct {}

type IQux interface {
    Compare(object interface{}) bool
}

type Qux struct {
    Method func(str string)
    Reference interface{}
}

func (qux Qux) Compare(object interface{}) bool {
    return object == qux.Reference
}

func testMethod(str string) {
    fmt.Println(str)
}

func main() {
    foo := Foo{TestMethod:testMethod}
    bar := Bar{}

    ob := &Qux{Method: foo.TestMethod, Reference: foo}

    ob.Compare(bar) // works fine
    ob.Compare(foo) // panic: runtime error: comparing uncomparable type main.Foo
}

1 个答案:

答案 0 :(得分:-1)

你有一点错字,试试吧:

package main

import "fmt"

type Foo struct {
    TestMethod func(str string)
}

type Bar struct {}

type IQux interface {
    Compare(object interface{}) bool
}

type Qux struct {
    Method func(str string)
    Reference interface{}
}

func (qux Qux) Compare(object interface{}) bool {
    return object == qux.Reference
}

func testMethod(str string) {
    fmt.Println(str)
}

func main() {
    foo := &Foo{TestMethod:testMethod}
    bar := Bar{}

    ob := Qux{Method: foo.TestMethod, Reference: foo}

    ob.Compare(bar) // works fine
    ob.Compare(foo) // panic: runtime error: comparing uncomparable type main.Foo
}