Skip to content

golang interface 比较

Posted on:September 18, 2019 at 09:05 PM

来源

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的时候,满足以下条件才能可比较:

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

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

相关分析