Skip to content

Instantly share code, notes, and snippets.

View tebeka's full-sized avatar
💭
alive

Miki Tebeka tebeka

💭
alive
View GitHub Profile
filePerm := Read | Write // set permission (| is bitwise OR)
if filePerm&Write != 0 { // check permission (& is bitwise AND)
fmt.Println("can write")
}
func (p FilePerm) String() string {
switch p {
case Read:
return "read"
case Write:
return "write"
case Execute:
return "execute"
}

Seeking Permission or Begging Forgiveness?

A Go Brain Teaser

What do you think the following program will print?

https://gist.github.com/cd76f0d470d06005166315e3f1a81845

This program will print: 4.

When you use iota in a const group, the values of the constants will advance according to the first operation. The << operator is "left shift". It moves the bits of a number to the left, basically multiplying it by power of 2.

type Perm struct {
Read bool
Write bool
Execute bool
}
fmt.Println(unsafe.Sizeof(filePerm)) // 1
var p Perm
fmt.Println(unsafe.Sizeof(p)) // 3
filePerm := Read | Write // set permission (| is bitwise OR)
if filePerm&Write != 0 { // check permission (& is bitwise AND)
fmt.Println("can write")
}
type FilePerm uint8
const (
Read FilePerm = 1 << iota
Write
Execute
)
func main() {
fmt.Println(Execute) // execute
func (p FilePerm) String() string {
switch p {
case Read:
return "read"
case Write:
return "write"
case Execute:
return "execute"
}
fmt.Println(unsafe.Sizeof(filePerm)) // 1
var p Perm
fmt.Println(unsafe.Sizeof(p)) // 3
type Perm struct {
Read bool
Write bool
Execute bool
}