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中 (对象 == 对象) 是一个道理的

既然2个指针所指向的内存都一样了,怎么可能不相等呢?

但是说了这么多,回到问题的本质,

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

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

这里又延伸出来一个知识点

struct可以作为map的key么?

答案:可以,也不可以

struct必须是可比较的,才能作为key,否则编译时报错

什么是可比较

文档规范:https://golang.org/ref/spec#Comparison_operators

<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官方博客 返回首页