4

In Go is it possible to define a custom type with a number of bits other than those offered by byte uint uint16 or any of the other built-in types?

I'm planning on using "just enough bits" to represent variables and wanted a 6-bit and a 4-bit type. Perhaps a composite bool type?

type fourbit struct{
    ones   bool
    twos   bool
    fours  bool
    eights bool
}

Though this sort of thing is quite messy and it would be nice to have a more general solution for n-bit types.

RoninDev
  • 5,446
  • 3
  • 23
  • 37
rigsby
  • 774
  • 7
  • 20
  • You might be looking for something like this; https://golang.org/pkg/encoding/binary/ you can store small values as a byte, not so sure about storing values that are one and a half bytes, you'll probably have to round up and put it in a 2byte buffer. – evanmcdonnal Oct 29 '15 at 22:03
  • A more common pattern in most programming languages (and used throughout Go) is a bitmap to hold up to 8 values per byte: http://play.golang.org/p/DZj9FerK19 – JimB Oct 30 '15 at 13:49

1 Answers1

6

No. The minimum size of a Go type in current implementations, including type bool, is one byte, .

References:

The Go Programming Language Specification

peterSO
  • 158,998
  • 31
  • 281
  • 276
  • 1
    [_basic addressable unit_](http://stackoverflow.com/a/4626993/2055586), interesting, very cool thanks for the quick reply. – rigsby Oct 29 '15 at 23:12