In Go, a normal struct typically occupies a block of memory. However, there's a special case: if it's an empty struct, its size is zero. How is this possible, and what is the use of an empty struct?
This article is first published in the medium MPP plan. If you are a medium user, please follow me in medium. Thank you very much.
type Test struct { A int B string } func main() { fmt.Println(unsafe.Sizeof(new(Test))) fmt.Println(unsafe.Sizeof(struct{}{})) } /* 8 0 */
The Secret of the Empty Struct
Special Variable: zerobase
An empty struct is a struct with no memory size. This statement is correct, but to be more precise, it actually has a special starting point: the zerobase variable. This is a uintptr global variable that occupies 8 bytes. Whenever countless struct {} variables are defined, the compiler assigns the address of this zerobase variable. In other words, in Go, any memory allocation with a size of 0 uses the same address, &zerobase.
Example
package main import "fmt" type emptyStruct struct {} func main() { a := struct{}{} b := struct{}{} c := emptyStruct{} fmt.Printf("%p\n", &a) fmt.Printf("%p\n", &b) fmt.Printf("%p\n", &c) } // 0x58e360 // 0x58e360 // 0x58e360
The memory addresses of variables of an empty struct are all the same. This is because the compiler assigns &zerobase during compilation when encountering this special type of memory allocation. This logic is in the mallocgc function:
//go:linkname mallocgc func mallocgc(size uintptr, typ *_type, needzero bool) unsafe.Pointer { ... if size == 0 { return unsafe.Pointer(&zerobase) } ...
This is the secret of the Empty struct. With this special variable, we can accomplish many functionalities.
Empty Struct and Memory Alignment
Typically, if an empty struct is part of a larger struct, it doesn't occupy memory. However, there's a special case when the empty struct is the last field; it triggers memory alignment.
Example
type A struct { x int y string z struct{} } type B struct { x int z struct{} y string } func main() { println(unsafe.Alignof(A{})) println(unsafe.Alignof(B{})) println(unsafe.Sizeof(A{})) println(unsafe.Sizeof(B{})) } /** 8 8 32 24 **/
When a pointer to a field is present, the returned address may be outside the struct, potentially leading to memory leaks if the memory is not freed when the struct is released. Therefore, when an empty struct is the last field of another struct, additional memory is allocated for safety. If the empty struct is at the beginning or middle, its address is the same as the next variable.
type A struct { x int y string z struct{} } type B struct { x int z struct{} y string } func main() { a := A{} b := B{} fmt.Printf("%p\n", &a.y) fmt.Printf("%p\n", &a.z) fmt.Printf("%p\n", &b.y) fmt.Printf("%p\n", &b.z) } /** 0x1400012c008 0x1400012c018 0x1400012e008 0x1400012e008 **/
Use Cases of the Empty Struct
The core reason for the existence of the empty struct struct{} is to save memory. When you need a struct but don't care about its contents, consider using an empty struct. Go's core composite structures such as map, chan, and slice can all use struct{}.
map & struct{}
// Create map m := make(map[int]struct{}) // Assign value m[1] = struct{}{} // Check if key exists _, ok := m[1]
chan & struct{}
A classic scenario combines channel and struct{}, where struct{} is often used as a signal without caring about its content. As analyzed in previous articles, the essential data structure of a channel is a management structure plus a ring buffer. The ring buffer is zero-allocated if struct{} is used as an element.
The only use of chan and struct{} together is for signal transmission since the empty struct itself cannot carry any value. Generally, it's used with no buffer channels.
// Create a signal channel waitc := make(chan struct{}) // ... goroutine 1: // Send signal: push element waitc <p>In this scenario, is struct{} absolutely necessary? Not really, and the memory saved is negligible. The key point is that the element value of chan is not cared about, hence struct{} is used.</p> <h3> Summary </h3> <ol> <li>An empty struct is still a struct, just with a size of 0.</li> <li>All empty structs share the same address: the address of zerobase.</li> <li>We can leverage the empty struct's non-memory-occupying feature to optimize code, such as using maps to implement sets and channels.</li> </ol> <h3> References </h3> <ol> <li>The empty struct, Dave Cheney</li> <li>Go 最细节篇— struct{} 空结构体究竟是啥?</li> </ol>
以上是解密Go:空結構的詳細內容。更多資訊請關注PHP中文網其他相關文章!

OpenSSL,作為廣泛應用於安全通信的開源庫,提供了加密算法、密鑰和證書管理等功能。然而,其歷史版本中存在一些已知安全漏洞,其中一些危害極大。本文將重點介紹Debian系統中OpenSSL的常見漏洞及應對措施。 DebianOpenSSL已知漏洞:OpenSSL曾出現過多個嚴重漏洞,例如:心臟出血漏洞(CVE-2014-0160):該漏洞影響OpenSSL1.0.1至1.0.1f以及1.0.2至1.0.2beta版本。攻擊者可利用此漏洞未經授權讀取服務器上的敏感信息,包括加密密鑰等。

本文演示了創建模擬和存根進行單元測試。 它強調使用接口,提供模擬實現的示例,並討論最佳實踐,例如保持模擬集中並使用斷言庫。 文章

本文探討了GO的仿製藥自定義類型約束。 它詳細介紹了界面如何定義通用功能的最低類型要求,從而改善了類型的安全性和代碼可重複使用性。 本文還討論了局限性和最佳實踐

本文討論了GO的反思軟件包,用於運行時操作代碼,對序列化,通用編程等有益。它警告性能成本,例如較慢的執行和更高的內存使用,建議明智的使用和最佳

本文討論了GO中使用表驅動的測試,該方法使用測試用例表來測試具有多個輸入和結果的功能。它突出了諸如提高的可讀性,降低重複,可伸縮性,一致性和A

本文使用跟踪工具探討了GO應用程序執行流。 它討論了手冊和自動儀器技術,比較諸如Jaeger,Zipkin和Opentelemetry之類的工具,並突出顯示有效的數據可視化


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

Dreamweaver Mac版
視覺化網頁開發工具

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能