xxxxxxxxxx
type ByteSize float64
const (
_ = iota // ignore first value by assigning to blank identifier
KB ByteSize = 1 << (10 * iota)
MB
GB
TB
PB
EB
ZB
YB
)
// String changes the default print
func (b ByteSize) String() string {
switch {
case b >= YB:
return fmt.Sprintf("%.2fYB", b/YB)
case b >= ZB:
return fmt.Sprintf("%.2fZB", b/ZB)
case b >= EB:
return fmt.Sprintf("%.2fEB", b/EB)
case b >= PB:
return fmt.Sprintf("%.2fPB", b/PB)
case b >= TB:
return fmt.Sprintf("%.2fTB", b/TB)
case b >= GB:
return fmt.Sprintf("%.2fGB", b/GB)
case b >= MB:
return fmt.Sprintf("%.2fMB", b/MB)
case b >= KB:
return fmt.Sprintf("%.2fKB", b/KB)
}
return fmt.Sprintf("%.2fB", b)
}
func main() {
fmt.Println(ByteSize(1e13)) // output: 9.09TB
}
/**
Constant and Enum in Golang:
- They are created at compile time, even when defined as
locals in functions, and can only be numbers,
characters (runes), strings or booleans.
- Because of the compile-time restriction, the expressions
that define them must be constant expressions, evaluatable
by the compiler. For instance, 1<<3 is a constant expression,
while math.Sin(math.Pi/4) is not because the function call
to math.Sin needs to happen at run time.
- In Go, enumerated constants are created using the iota
enumerator.
- Since iota can be part of an expression and expressions
can be implicitly repeated, it is easy to build intricate
sets of values.
**/
xxxxxxxxxx
// int mapping
const (
Summer int = 0
Autumn = 1
Winter = 2
Spring = 3
)
// string mapping
const (
Summer string = "summer"
Autumn = "autumn"
Winter = "winter"
Spring = "spring"
)
xxxxxxxxxx
package main
import "fmt"
type CustomType int
func (enum CustomType) Enum(index CustomType, data []string) string {
return data[index]
}
func main() {
// example one created enum type
const (
Admin = iota
User
Staff
)
var RolesEnum CustomType = Admin | User | Staff
data := []string{"Admin", "User", "Staff"}
fmt.Printf("enum version one %#v \n", RolesEnum.Enum(RolesEnum&Admin, data))
// example two created enum type
var EnumStatusList = struct {
Completed string
Rejected string
Error string
}{
Completed: "Completed",
Rejected: "Rejected",
Error: "Error",
}
fmt.Printf("enum version two %#v \n", EnumStatusList.Completed)
// example three created enum type
const (
Kucing = "Kucing"
Gajah = "Gajah"
Biawak = "Biawak"
)
fmt.Printf("enum version three %#v \n", Kucing)
}
xxxxxxxxxx
package main
import "fmt"
// using type
type RoleAllowed string
const (
admin RoleAllowed = "admin"
user RoleAllowed = "user"
)
// using specific type data
const (
supercar string = "lamborgini"
classiccar string = "camaro ss"
)
func main() {
// access enum like this
fmt.Println(classiccar)
}