Go结构比较 [英] Go struct comparison

查看:44
本文介绍了Go结构比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比较运算符上的 Go编程语言规范部分使我相信一个仅包含结构的结构可比较的字段应该是可比较的:

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


如果所有字段都是可比较的,则结构值是可比较的。如果两个对应的非空白字段相等,则两个struct值相等。

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:


无效操作:alice> =颂歌(运算符> =未在结构上定义)

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

我缺少什么?

推荐答案

您是正确的,结构是可比的,但不是有序的规范):

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.

这篇关于Go结构比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆