You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于语法variable <-struct {}{}中双{}含义的技术咨询

Understanding 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 a bool or 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 how int{42} creates an int instance with value 42—since our empty struct has no fields, we leave the inner braces empty, and this gives us a fully valid instance of struct{}.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:11:29