Skip to content

Instantly share code, notes, and snippets.

@udhos
Created April 29, 2019 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save udhos/165d7856b5104d800be3c3da6fe638db to your computer and use it in GitHub Desktop.
Save udhos/165d7856b5104d800be3c3da6fe638db to your computer and use it in GitHub Desktop.
golang_empty_struct
// the empty struct consumes zero bytes
// see: https://dave.cheney.net/2014/03/25/the-empty-struct
// see: https://github.com/bradfitz/iter
package main
import (
"fmt"
"strconv"
"unsafe"
)
func main() {
var emtpyStruct struct{}
fmt.Println("size of empty struct:", unsafe.Sizeof(emtpyStruct)) // prints 0
var x [1000000000]struct{}
fmt.Println("size of huge slice of empty structs:", unsafe.Sizeof(x)) // prints 0
s := N(5)
s[0] = struct{}{}
fmt.Println("len=" + strconv.Itoa(len(s)) + " cap=" + strconv.Itoa(cap(s)))
for i := range s {
fmt.Println(i)
}
}
func N(n int) []struct{} {
return make([]struct{}, n)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment