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?

  • 写回答

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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟