同类型struct比较情况

同类型struct的两个实例在不同的情况下可以也不可以用==或!=

如果结构体内的所有成员是可以比较的类型,那么可以比较,反正亦然

不同类型struct比较情况

不同类型struct的两个实例在不同的情况下可以也不可以用==或!=

如果想要比较两个不同的struct的实例的话,需要先进行结构类型的转换,转换成同一个结构类型才可以进行比较。
结构体之间进行转换需要他们具备完全相同的成员(字段名、字段类型、字段个数)

可比较的类型

  • 简单类型
  • 可排序类型
    • 整型
    • 浮点型
    • 字符
  • 其他
    • Boolean
    • Complex
    • Pointer
    • Channel
    • Interface
    • Array

不可比较的类型

  • Slice
  • Map
  • Function

相同类型struct测试示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package main

import (
	"fmt"
)

type Test struct {
	value int
}

func main() {
	t1 := Test{value: 1}
	t2 := Test{value: 1}
	t3 := Test{value: 2}

	fmt.Println(t1 == t2) // true
	fmt.Println(t2 == t3) // false
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package main

import (
    "fmt"
)

type Info struct {
	Str    string
	m      map[int]int
	weight int
}

func StructCantNotComparable() {
	p1 := Info{
		Str:    "wang",
		m:      make(map[int]int),
		weight: 0,
	}
	p2 := Info{
		Str:    "wang",
		m:      make(map[int]int),
		weight: 0,
	}
	fmt.Println(p1 == p2) // 编译器会直接显示错误
}

func main() {
	
}

不相同类型struct测试示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main

import (
  "fmt"
)

func StructCantComparable() {
	
  type Info struct {
    value string
  }
  
  type InfoX struct {
    value string
  }
  
  a := Info{value: "111"}
  b := InfoX{value: "222"}
  
  fmt.Println(a == b)       // 不能比较,编译器报错
  fmt.Println(a == Info(b)) // 能比较, false
}


func main() {
  StructCantComparable()
}

摘自