https://github.com/goiste/bit_flags
A simple package to store up to 64 boolean flags in one uint field
https://github.com/goiste/bit_flags
bitwise boolean flags generics go golang uint
Last synced: about 2 months ago
JSON representation
A simple package to store up to 64 boolean flags in one uint field
- Host: GitHub
- URL: https://github.com/goiste/bit_flags
- Owner: goiste
- Created: 2022-08-09T17:41:20.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2022-08-10T06:44:22.000Z (almost 3 years ago)
- Last Synced: 2024-06-20T05:10:51.141Z (11 months ago)
- Topics: bitwise, boolean, flags, generics, go, golang, uint
- Language: Go
- Homepage:
- Size: 3.91 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Bit Flags
A simple package to store up to 64 boolean flags in one uint field.
Requires Go version 1.18+ (uses generics)
For usage example see [example dir](example)
```go
import (
"strings"bf "github.com/goiste/bit_flags"
)const (
Messages = 1 << iota // 1
Replies // 2
Likes // 4
NewArticles // ... powers of 2
NewsByEmail
BySms
ByTelegramAllNotifications = Messages | Replies | Likes | NewArticles | News
AllMethods = ByEmail | BySms | ByTelegram
)type Notification struct {
SomeOtherFields string
Flags bf.BitFlags[uint8]
}func New() *Notification { ... }
func (n *Notification) SetDefaultFlags() {
n.Flags.Set(Messages | Replies | Likes | ByEmail)
}func (n *Notification) SetAll() {
n.Flags.Set(AllNotifications | AllMethods)
}func (n *Notification) SetNone() {
n.Flags.Reset()
}...
```
[full notification.go](example/notification.go)
```go
func main() {
ntf := notification.New()
fmt.Println(ntf.Flags.Get()) // 39
fmt.Println(ntf.FlagsToString()) // Messages, Replies, Likes, By emailntf.Flags.Add(notification.News | notification.BySms)
ntf.Flags.Remove(notification.Replies | notification.Likes)
fmt.Println(ntf.FlagsToString()) // Messages, News, By email, By sms
fmt.Println(ntf.HasFlag(notification.Messages)) // true
fmt.Println(ntf.HasFlag(notification.Likes)) // falsentf.Flags.Reset()
fmt.Println(ntf.Flags.Get()) // 0
fmt.Println(ntf.GetFlagsNames()) // []ntf.SetAll()
fmt.Println(ntf.Flags.Get()) // 255
fmt.Println(ntf.FlagsToString()) // Messages, Replies, Likes, New articles, News, By email, By sms, By telegram
}
```
[full main.go](example/main.go)