Jason Liu
Jason Liu

Reputation: 818

golang comparing two structures with their interface arguments

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?

Upvotes: 2

Views: 4022

Answers (1)

Thundercat
Thundercat

Reputation: 121209

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
}

Upvotes: 4

Related Questions