Is the golang channel assignment shared?

when you look at the code of etcd raft, the readyc variable in node.run () is also assigned to node.readyc.
by the same token, when you put Ready into readyc, you can also read data from node.readyc.

does an experiment: the following code creates a channel c and a structure node that contains channel ch.
assign c to node.ch. Then put the data into c, why can you take the data out of node.ch?
is the channel shared? But the printed address does not show the same address.

func main() {
    c := make(chan int)

    n := &node{
        ch: make(chan int),
    }

    fmt.Println("c:", &c)
    fmt.Println("n:", &n.ch)

    // 
    c = n.ch

    fmt.Println("c:", &c)
    fmt.Println("n:", &n.ch)

    // c
    go func() {
        c <- 1
        c <- 2
    }()

    // c
    e := <-c
    fmt.Println("v1:", e)

    // n.ch
    d := <-n.ch
    fmt.Println("v2:", d)

    fmt.Println("c:", &c)
    fmt.Println("n:", &n.ch)
}

type node struct {
    ch chan int
}

sample output:

c: 0xc42000c028
n: 0xc42000c030
c: 0xc42000c028
n: 0xc42000c030
v1: 1
v2: 2
c: 0xc42000c028
n: 0xc42000c030
Jun.16,2021
Behind the

chan type are pointers
that regards c and node.ch as pointers
, then & c and & node.ch are both addresses to pointers
then the memory of ch and node.ch is allocated when it is created (allocation on the stack) and will not change


.
  1. chan is already a pointer.
c := make(chan int)

c is the pointer.
if you are & c, that's the pointer to c, so after the assignment you see, the pointer address of the pointer does not change.

After
  1. is assigned, c actually becomes n.ch. These two are the same pointer.
Menu