An introduction to the syntax of one way channel in golang
- 2020-06-12 09:17:13
- OfStack
This article is mainly about golang one-way channel grammar related content, share for your reference and study, the following words are not enough, let's have a look at the detailed introduction:
Today, be free and at leisure adds 1 golang grammar. When I think of the usage of context, I come across an channel grammar I haven't seen before:
// 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 time.Time, ok bool)
// Value returns the value associated with key or nil if none.
Value(key interface{}) interface{}
}
Now, look at:
Done() <- chan struct{}
How is the declaration of an interface function so strange? So let's factor 1.
Done() chan struct{}
: If the function definition is changed to this, the meaning is,
chan struct{}
.
Take the return value alone, it is 1 pipe chan, and the internal data type is
struct{}
.
Take struct{} alone, we are familiar with it
type Name struct{a int, b bool}
To define the type of a structure, struct{... } is the definition of the structure, and map[string]int this definition is the same, type just gives it an individual name.
<- chan struct{}
If we look at this expression alone, we know if
ch := make(chan struct{})
, then
<
-ch takes data from the pipe. but
chan struct{}
Type, not variable. Can you get data from a type?
Actually,
<-chan int
This is still a pipe type, which is called one-way channel. If it is
<-chan int
Can only read not write pipe (also cannot close), if is
Done() chan struct{}
0
Can only write unreadable pipe (can close), that's all!
conclusion