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 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?