Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go struct comparison

Tags:

The Go Programming Language Specification section on Comparison operators leads me to believe that a struct containing only comparable fields should be comparable:

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

As such, I would expect the following code to compile since all of the fields in the "Student" struct are comparable:

package main

type Student struct {
  Name  string // "String values are comparable and ordered, lexically byte-wise."
  Score uint8  // "Integer values are comparable and ordered, in the usual way."
}

func main() {
  alice := Student{"Alice", 98}
  carol := Student{"Carol", 72}

  if alice >= carol {
    println("Alice >= Carol")
  } else {
    println("Alice < Carol")
  }
}

However, it fails to compile with the message:

invalid operation: alice >= carol (operator >= not defined on struct)

What am I missing?

like image 480
maerics Avatar asked Sep 22 '16 15:09

maerics


People also ask

How do you compare two structs in Go?

In Go language, you are allowed to compare two structures if they are of the same type and contain the same fields values with the help of == operator or DeeplyEqual() Method.

What is _ struct {} in Golang?

A struct (short for "structure") is a collection of data fields with declared data types. Golang has the ability to declare and create own data types by combining one or more types, including both built-in and user-defined types.

How can I check if two slices are equal?

Slice values are deeply equal when all of the following are true: they are both nil or both non-nil, they have the same length, and either they point to the same initial entry of the same underlying array (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal.


1 Answers

You are correct, structs are comparable, but not ordered (spec):

The equality operators == and != apply to operands that are comparable. The ordering operators <, <=, >, and >= apply to operands that are ordered.

...

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

>= is an ordered operator, not a comparable one.

like image 150
Tim Cooper Avatar answered Oct 11 '22 05:10

Tim Cooper