[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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值