Go语言 struct结构体 能比较么 == 或 !=

同一个struct的2个实例能不能比较 ==  !=


两个不同的struct的实例能不能比较 ==  !=







t1 t2 是同一个struct的2个赋值相同的实例

他们本质就是结构体的一个“对象”,因为成员变量带有了不能比较的成员,所以只要写 == 就报错

t3 t4 虽然能用 == ,但是人家本质上是比较的指针类型,*t3 == *t4 一样的一写就报错


func DeepEqual(a1, a2 interface{}) bool


1: 指针1 == 指针2 结果为true

2: 指针1 指针2 所指向的值深度相等

满足其中的一条即 DeepEqual 结果为true

== 如果用来比较指针,比较的就是指针所指向的内存地址,而不是指针变量本身所在的内存地址

这一点你可以理解为和Java中 (对象 == 对象) 是一个道理的



虽然 DeepEqual方法可以达到比较值是否相等这样的效果,

但是对于结构体实例而言,因为含有不能比较的成员变量,所以 == 和 != 是不能用的







<div class="post-text" itemprop="text"> <p>I am new to go language, under learning. I have years OOP experience in C++. There is a stacker interface that is written in go and two implementations of it, one is slice base stack and another one is linkedlist base.</p> <p>I find it is hard to compare two different structures and tell if they are containing the same data or not. The simple example code list below (notice a lot of functions/implementations are not listed because they are not relative with this question). The key function is <strong>stackEquals</strong>, I have tried different ways to approach it but they failed. Please see the comments in the code.</p> <pre><code>package main import ( "fmt" "errors" ) // The interface is fixed, cannot be modified type Stacker interface { isEmpty() bool size() int push(x int) peek() (int, error) pop() (int, error) copy() Stacker } type StackSlice struct { slice []int } type StackLinked struct { next *StackLinked value int // possible with other variables that is not relative } // There are interface function/method implementations did not paste func (s StackSlice) String() string { // return all the value inside the stack as string // like [5 4] } func (s StackLinked) String() string { // return all the value inside the stack as string // like [5 4]] } // Pre-condition: // none // Post-condition: // returns true if s and t have the same elements in the same order; // both s and t have the same value after calling stackEquals as before // Annoying constraint: // Use only Stackers in the body of this functions: don't use arrays, // slices, or any container other than a Stacker. func stackEquals(s, t Stacker) bool { // This implementation below always return false unless they are the same thing return s == t // I tried return s.String() == t.String() but gave an error said interface doesn't have String() method. } </code></pre> <p>How can I compare two stacks that implemented in different way and tell if they are the same (same means same values in same order) in the stack.</p> </div>
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页