SoFunction
Updated on 2025-03-05

Introduction to the syntax of one-way channel in golang

This article mainly introduces relevant content about golang one-way channel grammar. We will share it for your reference and learning. Let’s not say much below, let’s take a look at the detailed introduction:

Today I have nothing to do and add to the grammar knowledge of golang. I remember to see the usage of context, but I encountered an unprecedented channel syntax:

// A Context carries a deadline, cancelation signal, and request-scoped values
// across API boundaries. Its methods are safe for simultaneous use by multiple
// goroutines.
type Context interface {
 // Done returns a channel that is closed when this `Context` is canceled
 // or times out.
 Done() <-chan struct{}
 
 // Err indicates why this Context was canceled, after the Done channel
 // is closed.
 Err() error
 
 // Deadline returns the time when this Context will be canceled, if any.
 Deadline() (deadline , ok bool)
 
 // Value returns the value associated with key or nil if none.
 Value(key interface{}) interface{}
}

Pay attention to:Done() <- chan struct{}, Why is the declaration of an interface function so strange? Let’s break it down below.

Done() chan struct{} : If the function definition is changed to this, its meaning is,

  • Function name Done, parameter(), return valuechan struct{}
  • Take the return value separately, it is a pipeline chan, and the internal data type isstruct{}
  • Take struct{} as an example, we are familiar with ittype Name struct{a int, b bool}To define the type of a structure in this way, struct{…} is actually to define the structure, which is the same as map[string]int, type just gives it an alias.

<- chan struct{}: Look at this expression alone, we know ifch := make(chan struct{}) , then <- ch is to retrieve data from the pipeline. butchan struct{}Is it a type rather than a variable, and can I actually get data from a type? ?

actually<-chan intIt is still a pipeline type, which is called a one-way channel. in the case of<-chan int, which means that it is a pipe that can only be read but not written (and cannot be closed).chan <- int, it means that it is a pipe that can only be written but not read (can be closed), that's all!

Summarize

The above is the entire content of this article. I hope that the content of this article will be of some help to everyone’s learning or using Go. If you have any questions, you can leave a message to communicate. Thank you for your support.