关于语法variable <-struct {}{}中双{}含义的技术咨询
variable <- struct{}{} in Go Hey there! Let me break down this Go syntax piece by piece so it makes total sense.
First, let's split the expression into its core parts: this is an operation to send an empty struct instance to a channel named variable. Here's what each part does:
struct{}: This defines an empty struct type in Go. It has no fields at all, which means it takes up 0 bytes of memory—super lightweight. We use this type when we just need to send a "signal" (like notifying a goroutine to finish, or triggering an event) without passing any actual data. It's more efficient than using aboolor other trivial types because it doesn't consume any memory.- The second
{}: This is the literal syntax to create an instance of that empty struct type. Think of it like howint{42}creates anintinstance with value 42—since our empty struct has no fields, we leave the inner braces empty, and this gives us a fully valid instance ofstruct{}.
Putting it all together: struct{}{} is just an instance of the empty struct type, and variable <- struct{}{} sends that instance to the channel variable (which must be declared as chan struct{} or a similar channel type).
A Quick Example
Here's a common use case—using an empty struct channel to wait for a goroutine to finish:
package main import ( "fmt" "time" ) func main() { // Create a channel that carries empty structs done := make(chan struct{}) // Launch a goroutine go func() { time.Sleep(2 * time.Second) fmt.Println("Goroutine finished its work!") // Send the "done" signal done <- struct{}{} }() // Wait until we receive the signal from the goroutine <-done fmt.Println("Main function can exit now.") }
In this case, we don't need to send any data—we just need to know when the goroutine is done, so the empty struct is perfect for the job.
内容的提问来源于stack exchange,提问作者heretolearn

