duanmianzhou5353
duanmianzhou5353
2016-09-22 15:34

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 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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dream_wu2015 dream_wu2015 5年前

    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.

    点赞 评论 复制链接分享
  • dtgr6303 dtgr6303 5年前

    You have to define the field you're comparing to get the program to compile.

    if alice.Score >= carol.Score
    

    Then it compiles and prints

    Alice >= Carol

    点赞 评论 复制链接分享

相关推荐