【发布时间】:2018-01-16 20:14:46
【问题描述】:
我目前正在学习 golang。我有 OOP 知识,尤其是 C++ 方面的知识。 这是示例代码: 主包
import "fmt"
type Person interface{
// Some other functions
}
type info struct {
Name string
Age int
}
type example struct {
Description string
Other int
}
func (p info) String() string {
return fmt.Sprintf("%v (%v years)", p.Name, p.Age)
}
func (p example) String() string {
return fmt.Sprintf("%v (%v years)", p.Description, p.Other)
}
// The argument cannot be changed
// Try not to access into Person because there will be other different structures
// that implement the Person interface
func compare(p1, p2 Person) bool {
return p1 == p2
}
func main() {
a := info{"Arthur Dent", 42}
z := info{"Zaphod Beeblebrox", 9001}
b := example{"Arthur Dent", 42}
fmt.Println(a, z)
fmt.Println(compare(a, b))
}
如你所见,有一个接口调用Person,由一个结构调用info实现。 Person 中有一些功能,但为了简化问题,我没有发布这些功能。现在的问题是我已经实现了方法 String for info 但比较函数将 Person 元素作为输入。
假设compare函数的声明不能更改,只在函数体中使用Person,如何解决问题或实现compara功能?
【问题讨论】:
-
使用
==比较值是否相等:func compare(p1, p2 Person) bool { return p1 == p2 }。这似乎很明显。也许问题是要求您向 Person 添加方法? -
你说得对,你能在下面输入它作为答案,并稍微解释一下为什么它可以只使用 p1 而不是函数调用吗?
-
我更新了一点代码,现在不行了。假设有另一个结构但具有相同的元素(可能以不同的顺序),我现在如何比较这两个对象?我正在 golang 中实现一个带有数组和链表的堆栈,并试图比较它们,即使它们在不同的实现中。如果它们来自不同的结构,它总是返回 false。
-
您在编辑中提出了不同的问题。我回答了最初的问题。
-
对不起,我将发布一个新问题
标签: go