简体   繁体   中英

Any repercussions from declaring a pointer to a channel in golang?

type Stuff {
    ch chan int
}

versus

type Stuff {
    ch *chan int
}

I know that channels are reference types & thus is mutable when returned by functions or as arguments. When is an address of a channel useful in a real world program ?

Perhaps your channel is used for rotating logs and you want to rotate (swap) logs; swap channel (log) pointers not values.

For example,

package main

import "fmt"

func swapPtr(a, b *chan string) {
    *a, *b = *b, *a
}

func swapVal(a, b chan string) {
    a, b = b, a
}

func main() {
    {
        a, b := make(chan string, 1), make(chan string, 1)
        a <- "x"
        b <- "y"
        swapPtr(&a, &b)
        fmt.Println("swapped")
        fmt.Println(<-a, <-b)
    }
    {
        a, b := make(chan string, 1), make(chan string, 1)
        a <- "x"
        b <- "y"
        swapVal(a, b)
        fmt.Println("not swapped")
        fmt.Println(<-a, <-b)
    }
}

Output:

swapped
y x
not swapped
x y

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