golang比较两个结构及其接口参数

时间:2018-01-16 20:14:47

标签: go

我正在学习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,由结构调用信息实现。在Person中有函数但是为了简化问题,我没有发布这些函数。现在的问题是我已经为info实现了String方法,但compare函数将Person元素作为输入。

假设比较函数的声明无法更改并且只使用此函数体中的Person,我该如何解决问题或实现compara功能?

1 个答案:

答案 0 :(得分:2)

specification says

  

界面值具有可比性。如果两个接口值具有相同的动态类型和相同的动态值,或者两者的值都为nil,则它们相等。

  

如果所有字段都具有可比性,则结构值具有可比性。如果相应的非空白字段相等,则两个struct值相等。

所有结构字段都具有可比性。

鉴于此,您可以使用等于运算符:

func compare(p1, p2 Person) bool { 
    return p1 == p2
}