type EventPrefs struct {
Call bool
Presence bool
Endpoint bool
VoiceMail bool
CallRecording bool
}
Currently, the size of that struct type is 5 bytes but I would like to use bits. Is there any way to do that?
There is no "bit" type in Go, so if you want to pack multiple
boolinformation into bits, you have to implement it yourself. Declare a field of typeuint8(oruint16or any other integer type), and provide methods that get / set specific bits of the field.General bit setting / clearing is as simple as this:
Packing your 5 bool fields into an
uint8value:Testing it:
Which outputs (try it on the Go Playground):
Is saving 4 bytes worth the hassle? Rarely.
Note: the above solution can have many variations. For example the masks can be "computed" using bitshifts, the
set()andget()functions could be methods ofEventPrefsand so thedataparameter would not be needed (andset()could directly set theEventPrefs.datafield so no return value would be needed either). Ifset()remains a function, thedataparam could be a pointer soset()could change the pointed value without returning the newdataetc. Thedatafield may have its own declared type e.g.bitpackwithget()andset()methods attached to it.See related: Difference between some operators "|", "^", "&", "&^". Golang