Skip to content

Instantly share code, notes, and snippets.

@inancgumus
Last active October 10, 2017 12:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inancgumus/28e4fb878e1b6688ef6e87142a5dab60 to your computer and use it in GitHub Desktop.
Save inancgumus/28e4fb878e1b6688ef6e87142a5dab60 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math"
"strconv"
)
// I used bitwise operations on iota.
// This will be handy when we want to represent months together.
// Like: April | May
type Month uint32
const (
January Month = 1 << iota // iota automatically increases by 1 on each line
February // 1 << 2
March // 1 << 3
April // 1 << 4
May // 1 << 5
June // ...
July
August
September
November
December
AllMonths = January | February | March | April | May | June | July | August |
September | November | December
)
// String returns the name of a month
//
// This attaches a method String to Month constant
//
// Tip: You can use Stringer to create string representation of enums automatically
// https://godoc.org/golang.org/x/tools/cmd/stringer
func (m Month) String() string {
names := []string{"January", "February", "March", "April", "May", "June",
"July", "August", "September", "November", "December"}
// if it's power of 2, then it's a singular Month value
if m&(m-1) == 0 {
// returns the index of the bit to select the month name from `names`
// array
return names[int(math.Log2(float64(m)))]
} else {
// for composites, just return its number
// exercise for you: return the names of the months in a composite Month
return strconv.Itoa(int(m))
}
}
func main() {
// for each month
for i := 1; i < 12; i++ {
month := Month((1 << uint(i-1)))
// name of the month: April.String()
// value of the month: April
//
// Printf automatically calls .String() method when it sees a %s
// Printf automatically converts to a numeric when it sees a %d
fmt.Printf("%s: %d\n", month, month)
}
// AllMonths contains all of the months
fmt.Println("All Months:", AllMonths)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment