Created
April 29, 2019 22:38
-
-
Save udhos/165d7856b5104d800be3c3da6fe638db to your computer and use it in GitHub Desktop.
golang_empty_struct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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