A channel in Go is a communication mechanism that allows one goroutine to send data to another safely, exemplified by using make(chan Type) to create it and the
In Go, a channel is a communication mechanism that allows one goroutine to send data to another goroutine safely. It’s a core feature of Go’s concurrency model, based on the idea of "Do not communicate by sharing memory; instead, share memory by communicating."

Channels are used to synchronize execution and pass data between goroutines without explicit locking.
What Is a Channel? (By Example)
Let’s break it down with a simple example, similar to what you’d see in "Go by Example":

package main import "fmt" func main() { // Create a channel of type string messages := make(chan string) // Send a value into the channel from a goroutine go func() { messages <- "hello" }() // Receive the value from the channel msg := <-messages fmt.Println(msg) // Output: hello }
Key Points:
make(chan Type)
creates a channel for values ofType
.- The
<-
operator sends and receives data:messages <- "hello"
sends the string"hello"
into the channel.msg := <-messages
receives a value from the channel and assigns it tomsg
.
Blocking Behavior
Channels are synchronous by default (also called unbuffered channels), meaning:
- A send operation blocks until another goroutine receives.
- A receive operation blocks until another goroutine sends.
This built-in blocking helps coordinate goroutines naturally.

Example:
ch := make(chan int) ch <- 5 // This will block if no one is receiving
→ This would cause a deadlock unless another goroutine is ready to receive.
Buffered Channels
You can create a buffered channel with a specified capacity:
ch := make(chan int, 2) ch <- 1 // doesn't block immediately ch <- 2 // still doesn't block // ch <- 3 // this would block, buffer full
- Sending only blocks when the buffer is full.
- Receiving blocks only when the buffer is empty.
Common Use Cases
- Worker pools: Distribute tasks across multiple goroutines.
- Signaling completion: Use a
done
channel to notify when a goroutine finishes. - Returning results from goroutines: Instead of using return values, send results back via a channel.
Example: Signaling completion
done := make(chan bool) go func() { fmt.Println("Working...") time.Sleep(time.Second) done <- true }() <-done // Wait until something is received fmt.Println("Done!")
Closing Channels
You can close a channel to indicate no more values will be sent:
close(ch)
Receivers can check if a channel is closed:
value, ok := <-ch if !ok { fmt.Println("Channel closed") }
Often used with range
to loop over incoming values:
for msg := range ch { fmt.Println(msg) }
Summary
A channel in Go is:
- A way to pass data between goroutines.
- A synchronization tool that avoids race conditions.
- Created with
make(chan Type)
ormake(chan Type, buffer)
. - Used with
to send and receive.
- Can be closed to signal completion.
It's central to writing clean, concurrent Go programs — and "Go by Example" uses simple, runnable code to show exactly how they work in practice.
Basically: channels = pipes between goroutines.
The above is the detailed content of what is a channel in go by example. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Go's switch statement will not be executed throughout the process by default and will automatically exit after matching the first condition. 1. Switch starts with a keyword and can carry one or no value; 2. Case matches from top to bottom in order, only the first match is run; 3. Multiple conditions can be listed by commas to match the same case; 4. There is no need to manually add break, but can be forced through; 5.default is used for unmatched cases, usually placed at the end.

In Go, to break out of nested loops, you should use labeled break statements or return through functions; 1. Use labeled break: Place the tag before the outer loop, such as OuterLoop:for{...}, use breakOuterLoop in the inner loop to directly exit the outer loop; 2. Put the nested loop into the function, and return in advance when the conditions are met, thereby terminating all loops; 3. Avoid using flag variables or goto, the former is lengthy and easy to make mistakes, and the latter is not recommended; the correct way is that the tag must be before the loop rather than after it, which is the idiomatic way to break out of multi-layer loops in Go.

Usecontexttopropagatecancellationanddeadlinesacrossgoroutines,enablingcooperativecancellationinHTTPservers,backgroundtasks,andchainedcalls.2.Withcontext.WithCancel(),createacancellablecontextandcallcancel()tosignaltermination,alwaysdeferringcancel()t

InitializeaGomodulewithgomodinit,2.InstallgqlgenCLI,3.Defineaschemainschema.graphqls,4.Rungqlgeninittogeneratemodelsandresolvers,5.Implementresolverfunctionsforqueriesandmutations,6.SetupanHTTPserverusingthegeneratedschema,and7.RuntheservertoaccessGr

Use a dedicated and reasonably configured HTTP client to set timeout and connection pools to improve performance and resource utilization; 2. Implement a retry mechanism with exponential backoff and jitter, only retry for 5xx, network errors and 429 status codes, and comply with Retry-After headers; 3. Use caches for static data such as user information (such as sync.Map or Redis), set reasonable TTL to avoid repeated requests; 4. Use semaphore or rate.Limiter to limit concurrency and request rates to prevent current limit or blocking; 5. Encapsulate the API as an interface to facilitate testing, mocking, and adding logs, tracking and other middleware; 6. Monitor request duration, error rate, status code and retry times through structured logs and indicators, combined with Op

Use the template.ParseFS and embed package to compile HTML templates into binary files. 1. Import the embed package and embed the template file into the embed.FS variable with //go:embedtemplates/.html; 2. Call template.Must(template.ParseFS(templateFS,"templates/.html")))) to parse all matching template files; 3. Render the specified in the HTTP processor through tmpl.ExecuteTemplate(w,"home.html", nil)

To correctly copy slices in Go, you must create a new underlying array instead of directly assigning values; 1. Use make and copy functions: dst:=make([]T,len(src));copy(dst,src); 2. Use append and nil slices: dst:=append([]T(nil),src...); both methods can realize element-level copying, avoid sharing the underlying array, and ensure that modifications do not affect each other. Direct assignment of dst=src will cause both to refer to the same array and are not real copying.

To import local packages correctly, you need to use the Go module and follow the principle of matching directory structure with import paths. 1. Use gomodinit to initialize the module, such as gomodinitexample.com/myproject; 2. Place the local package in a subdirectory, such as mypkg/utils.go, and the package is declared as packagemypkg; 3. Import it in main.go through the full module path, such as import "example.com/myproject/mypkg"; 4. Avoid relative import, path mismatch or naming conflicts; 5. Use replace directive for packages outside the module. Just make sure the module is initialized
