GO語言中結構體的(== 和 !=)比較


GO語言中結構體的比較

1. 同一個struct的兩個實例能用 == 或 != 來進行比較嗎

答案:可以能,也可以不能

如果結構體內的所有成員變量都是可以比較的,那么結構體就可以進行比較。

如果結構體中存在不可以比較的成員變量那么結構體就不能進行比較。

那么哪些數據類型是可以比較的呢?

1. 簡單類型

2. 可排序的數據類型

1. 整型
2. 浮點型
3. 字符串

3. 其他可比較類型

Boolean
Complex
Pointer
Channel     // 注意Channel 是可以進行比較的
Interface   // 接口
Array   

不可比較類型

Slice 
Map
Function

可比較的結構體例子

package main

import "fmt"

type User struct {
	a int
}

func main() {
	a := User{a:1}
	b := User{a:1}
	c := User{a:2}

	fmt.Println(a == b) // true
	fmt.Println(b == c) // false
}

加入不可比較的復雜類型

type People struct {
	name   string
	m      map[int]int
	weight int
}

func CantNotComparable() {
	p1 := People{
		name:   "wang",
		m:      make(map[int]int),
		weight: 0,
	}
	p2 := People{
		name:   "wang",
		m:      make(map[int]int),
		weight: 0,
	}
	fmt.Println(p1 == p2)  // 此時編譯器會直接顯示錯誤 無法編譯通過
}

如果此時其改為指向結構體的指針,此時報錯提示會取消,因為此時實際上相當於在比較兩個指針類型的變量

func CantNotComparable() {
	p1 := &People{
		name:   "wang",
		m:      make(map[int]int),
		weight: 0,
	}
	p2 := &People{
		name:   "wang",
		m:      make(map[int]int),
		weight: 0,
	}
	fmt.Println(&p1, &p2)
	fmt.Println(p1 == p2)
}

2. 兩個不同的struct的實例能不能比較 == !=

答案:可以能,也可以不能

如果想要比較兩個不同的struct的實例的話,需要先進行結構類型的轉換
轉換成同一個結構類型才可以進行比較

結構體之間進行轉換需要他們具備完全相同的成員(字段名、字段類型、字段個數)
func CantNotComparable() {
	p1 := People{
		name:   "wang",
		weight: 0,
	}
	p2 := User{
		name:   "wang",
		weight: 1,
	}
	p3 := People(p2)  // 進行結構體轉換
	fmt.Println(p1 == p3)
}

參考內容

https://blog.csdn.net/jcetpoor/article/details/108946530

https://blog.csdn.net/daima_caigou/article/details/91418969


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM