Saturday, 13 March 2021

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.



No comments:

Post a Comment

Difference between "docker stop" and "docker kill"

 To stop a running container, you can use either "docker stop" or "docker kill" command to do so. Although it seems doin...