3 ms·
FTA: “In Go, empty structs occupy zero bytes. The Go runtime handles all zero-sized allocations, including empty structs, by returning a single, special memory
by Someone 1y ago
FTA: “In Go, empty structs occupy zero bytes. The Go runtime handles all zero-sized allocations, including empty structs, by returning a single, special memory address that takes up no space.
This is why they’re commonly used to signal on channels when you don’t actually have to send any data. Compare this to booleans, which still must occupy some space.”
I would expect the compiler to ensure that all references to true and false reference single addresses, too. So, at best, the difference of the more obscure code is to, maybe, gain 8 bytes. What do I overlook?
- Zambyte 1y ago> I would expect the compiler to ensure that all references to true and false reference single addresses, too. Why? If you're sending a constant true to a channel, wouldn't that true value exist in the stack frame for the function call? It seems like that would make more sense than a pointer to a constant true value being stored in the stack frame and dereferencing that every time you need the constant value. > So, at best, the difference of the more obscure code is to, maybe, gain 8 bytes. What do I overlook? Constructing channels in a loop would potentially multiply memory usage here
- arccy 1y agoit's also so that there's no confusion about what the value represents.
- h4ck_th3_pl4n3t 1y agoGo is copy by default. That means it would work if *bool is possible but it's not.
- giancarlostoro 1y agoIf they did it without you explicitly making bool a pointer, then it would be syntactic sugar and it would kind of fall away from the spirit of Go which is, if you look at a file everything that's happening is known to you, there's no metaprogramming witchcraft anywhere in sight usually.
- tczMUFlmoNk 1y agoIf you have a buffered channel with 100 "true"s in it, you're using 100 bytes. If you have a buffered channel with 100 "struct{}{}"s in it, you only need to store the length, since the element type is zero-sized.
- Someone 1y agoSo, you’re having a channel through which you can only ever send "struct{}{}"s? If the compiler has an optimization to turn that into a single int, can’t it do the same for a channel that can only send other kinds of unique values? That would allow for more readable code.
- tczMUFlmoNk 1y agoSure. If T is a zero sized type, then chan T should just be an atomic int. I am not sure how much this improves code readability in practice—I see chan struct{} frequently, but I cannot recall ever having seen chan T for a zero-sized T other than struct{}.
- deleted 1y ago[deleted]
- foldr 1y agoThat wouldn’t work because boolean variables can be mutated (whereas you can’t mutate a zero-sized value).