Skip to content

Instantly share code, notes, and snippets.

@knaveightt
Last active February 17, 2023 19:49
Show Gist options
  • Save knaveightt/60f37da7422070a5a9d891c5041a47f8 to your computer and use it in GitHub Desktop.
Save knaveightt/60f37da7422070a5a9d891c5041a47f8 to your computer and use it in GitHub Desktop.
Learn Go - Primitives Summary
// Primitives Examples
package main
import "fmt"
func main() {
var n bool = true
var m bool // zero value is false
fmt.Printf("%v, %T\n", n, n)
fmt.Printf("%v, %T\n", m, m)
o := 42 // basic int type, at least 32 bits
// other options are below (SIGNED)
// int8 (-128 to +127)
// int16
// int32
// int64
var p uint16 = 42
fmt.Printf("%v, %T\n", o, o)
fmt.Printf("%v, %T\n", p, p)
// unsigned integers include
// uint8 (0 to 255)
// uint16
// uint32
// byte (alias for uint8, just because they are so common)
// basic arithmetic options exist, but an only do arithmetic on same types
var a int = 10
var b int8 = 3
fmt.Println(a + int(b))
var c byte = 10 // 00001010
var d byte = 3 // 00000011
fmt.Println(c & d) // 00000010
fmt.Println(c | d) // 00001011
fmt.Println(c ^ d) // 00001001
fmt.Println(c &^ d) // 0100
fmt.Println(d << 3)
fmt.Println(d >> 3)
f := 3.14 // will always be float64, but you can use float32 too
fmt.Println(f)
f = 13.7e10
fmt.Println(f)
var g complex64 = 1 + 2i
fmt.Printf("%v, %T\n", g, g)
fmt.Printf("%v, %T\n", real(g), real(g)) // complex64 decomposes to float32s
fmt.Printf("%v, %T\n", imag(g), imag(g)) // complex128 decomposes to float64s
s := "this is a string" // strings are immutable
fmt.Printf("%v, %T\n", s, s)
fmt.Printf("%v, %T\n", s[2], s[2]) // strings are alias's for bytes
fmt.Printf("%v, %T\n", string(s[2]), string(s[2]))
// convert to a slice of bytes
t := []byte(s) // "collection" of "byte"s, string s
fmt.Printf("%v, %T\n", t, t)
// runes are unicode 32 vs strings are unicode 8
u := 'a'
fmt.Printf("%v, %T\n", u, u)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment