简体   繁体   中英

What is the Go equivalent of Python's “is” operator?

How do I determine whether 2 variables refer to the same instance in Go? More specifically, that a mutation to the value of one variable would effect the value of the other variable also.

To further refine the question: How would I determine when 2 variables would satisfy the "is" operator per CPython:

a is b

EDIT : I'm not sure about what you want. If it's about the equality of variables or the identity of variable values. This answer is for the second one ("2 variables refer to the same instance " of value). If I misunderstood, I'll remove this answer.

== is what you want, I think.

If the type of a and b is pointer, then a==b means that a and b are pointers to the same value.

The following program prints false :

package main

import "fmt"

type test struct {
    a int
}

func main() {

    b := &test{2}
    c := &test{2}
    fmt.Println(c == b)

}

While this prints true :

    b := &test{2}
    c := b
    fmt.Println(c == b)

c==b is a sufficient condition for that changing ca changes ba

In Python, all values are references (ie pointers) to objects. You can never get an object itself as a value. The is operator compares two values, which are pointers, for pointer equality; whereas the == operator compares two such pointers, for equality of the objects pointed to.

In Go, it's a little more complicated. Go has pointers, as well as other non-pointer types (boolean, number types, strings, arrays, slices, structs, functions, interfaces, maps, channels). It doesn't make sense to ask for pointer equality for non-pointer types. (What would it mean? What would it accomplish?)

So to have the equivalent situation as Python, let's put all of our values behind pointers, and so all variables are pointers. (There is a convention in many Go libraries of a "New" function that creates a pointer type; and the methods also operate on the pointer type; so this is compatible with that convention.) Then (if a and b are pointers) a == b in Go would compare two such pointers for pointer equality; and you can use *a == *b to compare the underlying values, if they are comparable.

Go also has several non-pointer reference types: slices, maps, functions, and channels. Channels are comparable using == for whether they are the same channel. However, slices, maps, and functions cannot be compared; it may be possible using reflection though.

In case of non interface and non function types it is possible to compare pointers for equality. Non pointer types cannot share instances, OTOH.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM