英文:
How can I make two objects comparable
问题
我正在为你翻译以下内容:
我正在将两个不同结构的对象传递给一个函数,该函数将其与保存为interface {}
类型的现有对象进行比较。
在下面的代码中,我该如何使两个对象可以进行相等性比较===
?
在这个尝试中,与bar
的比较正常工作,但与foo
的比较会引发恐慌错误,尽管这两个对象都是结构类型。
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) // 正常工作
ob.Compare(foo) // 报错:运行时错误:比较不可比较的类型 main.Foo
}
你可以在Go Playground上查看代码。
英文:
I'm passing objects of two different structs to a function where it's compared with an existing object saved as interface {}
type.
In the following how can I make two objects comparable for Equality ===
In this attempt, comparison with bar works fine but with foo it throws a panic error in spite both objects are of struct type
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
得分: -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) // 正常工作
ob.Compare(foo) // 报错: 运行时错误: 比较不可比较的类型 main.Foo
}
英文:
You have a little typo, just try:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论