Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Go struct能不能比较 #5

Open
qloog opened this issue Jul 4, 2020 · 0 comments
Open

Go struct能不能比较 #5

qloog opened this issue Jul 4, 2020 · 0 comments
Labels

Comments

@qloog
Copy link
Contributor

qloog commented Jul 4, 2020

比较原则:

  • 如果结构体的所有成员变量都是可比较的,那么结构体就可比较
  • 如果结构体中存在不可比较的成员变量,那么结构体就不能比较
  • 结构体之间进行转换需要他们具备完全相同的成员(字段名、字段类型、字段个数)

具体哪些可以比较,可以参看官方文档:Comparison operators

相同struct

不可比较

可以比较

不同struct

不可比较

可以比较

比较两个 slice/struct/map 是否相等

可以通过 reflect.DeepEqual 比较两个 slice/struct/map 是否相等

package main

import (
    "fmt"
    "reflect"
)

type A struct {
    s string
}

func main() {

    a1 := A{s: "abc"}
    a2 := A{s: "abc"}
    if reflect.DeepEqual(a1, a2) {
        fmt.Println(a1, "==", a2)
    }

    b1 := []int{1, 2}
    b2 := []int{1, 2}
    if reflect.DeepEqual(b1, b2) {
        fmt.Println(b1, "==", b2)
    }

    c1 := map[string]int{"a": 1, "b": 2}
    c2 := map[string]int{"a": 1, "b": 2}
    if reflect.DeepEqual(c1, c2) {
        fmt.Println(c1, "==", c2)
    }
}

在线演示地址: http://play.golang.org/p/SB8LeLNdA8

Reference

@qloog qloog added the Golang label Jul 4, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant