Skip to main content

golang interface 比较

· 2 min read

来源

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.
A value x of non-interface type X and a value t of interface type T are comparable when values of type X are comparable and X implements T. They are equal if t's dynamic type is identical to X and t's dynamic value is equal to x.

A comparison of two interface values with identical dynamic types causes a run-time panic if values of that type are not comparable. This behavior applies not only to direct interface value comparisons but also when comparing arrays of interface values or structs with interface-valued fields.

interface 是可以比较的,当两个interface满足以下之一的时候两者相等:

  • 两个interface的动态类型和动态值两两相等
  • 两个interface值都是nil

当一个是interface,一个不是interface的时候,满足以下条件才能可比较:

  • x 是类型X的值,t是类型T的值。只有X是可比较且X是T的实现的时候,x和t是可比较的

那么当一个是interface,一个不是interface的时候,可比较的时候,怎么样才能相等呢?

  • 当t的动态类型和X相同且t的动态值与x相同

当比较两个interface的时候,如果他们的类型是不可比较的,那么会产生运行时panic,这种panic不仅仅会发生在interface直接比较。还会发生在interface数组比较或者包含interface作为structs中的字段时候的structs之间的比较。

相关分析