Skip to content

Instantly share code, notes, and snippets.

@knaveightt
Created February 17, 2023 21:07
Show Gist options
  • Save knaveightt/d6608d15edeb29b3eb715add31bb3526 to your computer and use it in GitHub Desktop.
Save knaveightt/d6608d15edeb29b3eb715add31bb3526 to your computer and use it in GitHub Desktop.
Learn Go - Constants Summary
// Constants Examples
package main
import "fmt"
// enumerated constants
const (
e1 = iota
e2 // it is inferring iota
e3 // it is inferring iota
)
const (
e4 = iota // will always start at 0 as the block. Typically you want 'zero' to indicate a value not assigned
e5 // if you are checking to see if something equials a particular constant
e6
)
const (
_ = iota // similar to the above, but throwing away the 0 value. you can also change
e7 // where iota starts by adding to it i.e. iota+5
e8
)
const (
_ = iota // example of assigning constants to size values
KB = 1 << (10 * iota)
MB
GB
TB
PB
EB
ZB
YB
)
const (
isAdmin = 1 << iota // 00000001
isHeadquarters // 00000010
canSeeFinancials // 00000100
canSeeAfrica // 00001000
canSeeAsia
canSeeEurope
canSeeNorthAmerica
canSeeSouthAmerica
)
func main() {
const myConst int = 42 // still use camel case, this is a typed constant
fmt.Printf("%v, %T\n", myConst, myConst)
const a = 42 // compiler can infer, including when using in calculations because
var b int16 = 27 // it is just replacing the name 'a' with the value 42 in this code essentially
fmt.Printf("%v, %T\n", a, a)
fmt.Printf("%v, %T\n", a+b, a+b)
// enumerated constants
fmt.Printf("%v, %T\n", e1, e1)
fmt.Printf("%v, %T\n", e2, e2)
fmt.Printf("%v, %T\n", e3, e3)
fmt.Printf("%v, %T\n", e4, e4)
fmt.Printf("%v, %T\n", e5, e5)
fmt.Printf("%v, %T\n", e6, e6)
fmt.Printf("%v, %T\n", e7, e7)
fmt.Printf("%v, %T\n", e8, e8)
var roles byte = isAdmin | canSeeFinancials | canSeeEurope
fmt.Printf("%b\n", roles)
fmt.Printf("Is Admin? %v\n", isAdmin&roles == isAdmin)
fmt.Printf("Is Headquarters? %v\n", isHeadquarters&roles == isHeadquarters)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment