From ec8f7901ad76242a7451a328b6ccf14b5fad15f3 Mon Sep 17 00:00:00 2001 From: "jiandong.liu" Date: Fri, 1 Sep 2023 11:09:57 +0800 Subject: [PATCH] post: add go empty struct --- content/posts/2023/09/_index.md | 5 +++ content/posts/2023/09/go_empty_struct.md | 45 ++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 content/posts/2023/09/_index.md create mode 100644 content/posts/2023/09/go_empty_struct.md diff --git a/content/posts/2023/09/_index.md b/content/posts/2023/09/_index.md new file mode 100644 index 0000000..8b7cedd --- /dev/null +++ b/content/posts/2023/09/_index.md @@ -0,0 +1,5 @@ +--- +weight: 1 +bookCollapseSection: true +title: "09" +--- diff --git a/content/posts/2023/09/go_empty_struct.md b/content/posts/2023/09/go_empty_struct.md new file mode 100644 index 0000000..63fb0eb --- /dev/null +++ b/content/posts/2023/09/go_empty_struct.md @@ -0,0 +1,45 @@ +--- +author: "jdlau" +date: 2023-09-01 +linktitle: Go Empty Struct +menu: +next: +prev: +title: Go Empty Struct +weight: 10 +categories: ['Go'] +tags: ['mark'] +--- + +```go +package main + +import ( + "fmt" + "unsafe" +) + +func main() { + type A struct{} + type B struct{} + // 结构体里的字段都是`Empty Struct`时,占用空间为0 + type S struct { + A A + B B + } + var s S + fmt.Println(unsafe.Sizeof(s)) // prints 0 + // 如果是指针,占用空间为8 + fmt.Println(unsafe.Sizeof(&s)) // prints 8 + + var x [1000000000]struct{} + // 可以同时存储A和B类型元素 + x[0] = A{} + x[1] = B{} + fmt.Println(unsafe.Sizeof(x)) // prints 0 + // 地址一样 + fmt.Printf("%p, %p", &x[0], &x[1]) // 0x54e3a0, 0x54e3a0 +} +``` + +[See also](https://dave.cheney.net/2014/03/25/the-empty-struct)