Bit manipulation using Enum in Go

 This method is learned from Youtube online course https://www.youtube.com/watch?v=YS4e4q9oBaU&t=5713s

Sometimes developers may want to use one byte to represent a combination of settings. In this case, each bit represents "Yes" or "No". 

So here you can use Enum in Go to define each bit with special meaning quickly. This allows us to manipulate each bit efficiently.

Below is an example code from the video I mentioned in the top.

package main

import (
"fmt"
)

const (
isAdmin = 1 << iota
isHeadquarters
canSeeFinancials

canSeeAfrica
canSeeAsia
canSeeEurope
canSeeNorthAmerica
canSeeSouthAmerica
)

func main() {
var roles byte = isAdmin | canSeeFinancials | canSeeEurope
fmt.Printf("%b\n", roles)

fmt.Printf("Is Admin? %v", isAdmin&roles == isAdmin)
}

The output is:

100101 Is Admin? true


This is a very good way to manage a set of settings like role management, access right management and so on.



Comments

Popular posts from this blog

Basic understanding of TLS-PSK protocol

Differences between ASIC, ASSP and ASIP

Orthogonal instruction set