du5910
2018-01-16 20:14
浏览 144
已采纳

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

I am currently studying golang. I have OOP knowledge especially on C++. Here is the example code: package main

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))
}

As you can see, there is a interface call Person, implemented by a structure call info. There are functions in Person but for simplifying the question, I didn't post those. The problem now is I have implemented the method String for info but the compare function takes Person elements as input.

Suppose the declaration of the compare function cannot be changed and use only Person in the body of this functions, how can I solve the problem or achieve the compara functionality?

图片转代码服务由CSDN问答提供 功能建议

我目前正在学习golang。 我具有OOP知识,尤其是C ++。 这是示例代码: package main

  import“ fmt” 
 
type Person接口{
 //其他功能 
} 
 
类型信息结构{
名称字符串
年龄int 
} 
 
类型示例结构{
描述字符串
其他int 
} 
 
func(p info)String() 字符串{
 return fmt.Sprintf(“%v(%v years)”,p.Name,p.Age)
} 
 
func(p示例)String()字符串{
返回fmt.Sprintf(  “%v(%v年)”,p.Description,p.Other)
} 
 
 //无法更改参数
 //尝试不要访问Person,因为会有其他不同的结构\  n //实现了Person接口的人
func compare(p1,p2 Person)bool {
 return p1 == p2 
} 
 
func main(){
a:= info {“ Arthur Dent”,42}  
z:=信息{“ Zaphod Beeblebrox”,9001} 
b:=例子{“ Arthur Dent”,42} 
 fmt.Println(a,z)
 fmt.Println(compare(a,b))\  n} 
   
 
 

如您所见,有一个接口Person,由结构c实现 所有信息。 Person中有一些功能,但是为了简化问题,我没有发布这些功能。 现在的问题是我已经为信息实现了String方法,但是compare函数将Person元素作为输入。

假设不能更改compare函数的声明,并且仅在正文中使用Person 这些功能中,我该如何解决问题或实现比较功能?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dongzhi1949 2018-01-16 20:23
    最佳回答

    The specification says:

    Interface values are comparable. Two interface values are equal if they have identical dynamic types and equal dynamic values or if both have value nil.

    and

    Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.

    All of the struct fields are comparable.

    Given this, you can use the equal operator:

    func compare(p1, p2 Person) bool { 
        return p1 == p2
    }
    
    评论
    解决 无用
    打赏 举报