本文介绍了检查接口的平等{}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为给定的界面{} 值搜索 [] interface {} 片段:

  var v interface {} 
for i:= 0;我< LEN(A); i ++ {
if(A [i] == v){
fmt.Println(Gotcha!)
break
}
}

在普通情况下,类型是 int 。然而,我应该怎么做,例如,类型是一些自定义 struct

解决方案

感谢@CodingPickle评论,我从

关于界面{} s和 structs




  • 接口值具有可比性。如果两个接口值具有相同的动态类型和相同的动态值,或者两者的值均为零,那么两个接口值相等。

  • 非接口类型X的值x和接口类型T的值t如果类型X的值是可比的,并且X实现了T,那么它们是可比的。如果t的动态类型与X完全相同,并且t的动态值等于x,则它们是相等的。
  • 所有的领域都是可比的。如果相应的非空白字段相等,则两个结构值相等。



换句话说,在Go中处理平等似乎很容易!

I am searching a []interface{} slice for a given interface{} value:

var v interface{}
for i := 0; i < len(A); i++ {
  if (A[i] == v) {
    fmt.Println("Gotcha!")
    break
  }
}

In the trivial case the types are int. However what should I do if, for example, the types are some custom struct?

解决方案

Thanks to @CodingPickle comment, I provide the following from the Go Programming Language Specification

Regarding interface{}s and structs:

  • 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.
  • Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.

In other words, handling equality seems easy in Go!

这篇关于检查接口的平等{}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 17:59