Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: comparing anonymous structs

Tags:

go

I don't understand how go compares anonymous structures. I am trying to understand this piece of code:

package main

import (
    "fmt"
)

type foo struct {
    bar string
}

func main() {
    var x struct {
        bar string
    }
    var y foo
    fmt.Println(x == y) // this prints true
    equals(x, y) // this prints false

}


func equals(a, b interface{}) {
    fmt.Println(a == b)
}

Why does x == y yields true? They have a different type, so I would expect that they cannot be compared.

And, as they are equal, why casting them to interface{} makes them unequal?

like image 878
Paperback Writer Avatar asked Feb 08 '23 05:02

Paperback Writer


1 Answers

Why does x == y yields true?

From the Go language specification:

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

The zero-value for a string is "", so x.bar and y.bar are equal, and therefore x and y are equal.


why casting them to interface{} makes them unequal?

Again, from the same page in the language specification:

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.

like image 107
Michael Avatar answered Feb 11 '23 21:02

Michael