[Go] 结构体/结构体指针是否可以比较 与 operator == is not defined 错误

同一个struct的2个实例能不能比较 == !=
答案:可以能、也可以不能

两个不同的struct的实例能不能比较 == !=
答案:可以能、也可以不能

如果结构体的所有成员变量都是可比较的,那么结构体就可比较
如果结构体中存在不可比较的成员变量,那么结构体就不能比较

    type s2 struct {
        name string
    }
    aa := s2{
        name: "aa",
    }
    bb := s2{
        name: "aa",
    }
    fmt.Printf("%v\n", aa == bb)

这个返回true

如果是结构体指针 , 返回 false

 

当有不可比较字段的时候 , 编译期就会报错

 

 换成结构体指针 , 就不会报错了

 

 返回结果 false;true

代码:

    type s1 struct {
        one   map[string]string
        two   []string
        three string
    }

    a := &s1{
        one:   map[string]string{"aaa": "bbb"},
        two:   []string{"aaa", "bbb"},
        three: "aaaa",
    }
    b := &s1{
        one:   map[string]string{"aaa": "bbb"},
        two:   []string{"aaa", "bbb"},
        three: "aaaa",
    }
    c := a
    fmt.Printf("%v;%v", a == b, a == c)

 

posted @ 2021-04-29 10:39  唯一客服系统开发笔记  阅读(357)  评论(0编辑  收藏  举报