welcome to my cheatsheet collection
find more of my stuff on codeberg or my website
this website was made using john-doe
basics
recommended reading
functions
func add(x, y int) int {
return x + y
}
func main() {
fmt.Println(add(42, 13))
// 55
}
variables
var msg string var msg = "Hello," var msg string = "world!" var x, y int var x, y int = 1, 2 msg := "Hello"
basic types
bool // true, false string // "hello world" int // 1, 2, 3 byte // 'A' rune // '⌘'
constants
const Phi = 1.618 const Size int64 = 1024 const x, y = 1, 2 const ( Pi = 3.14 E = 2.718 ) const ( Sunday = iota Monday Tuesday Wednesday Thursday Friday Saturday )
flow
for loops
func main() {
sum := 0
for i := 0; i < 10; i++ {
sum += i
}
fmt.Println(sum)
// 45
}
if
func sqrt(x float64) string {
if x < 0 {
return sqrt(-x) + "i"
}
return strconv.Itoa(math.Sqrt(x))
}
while loops
func main() {
sum := 1
for sum < 1000 {
sum += i
}
fmt.Println(sum)
// 1024
}
switch statements
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("macOS")
case "linux":
fmt.Println("Linux")
default:
fmt.Println(os)
}
switch statements do not need a condition, which
can be helpful for long if-then-else chains
infinite loops
func main() {
for {
}
}
defer
func main() {
defer fmt.Println("world")
fmt.Println("hello")
// "hello"
// "world"
}
defers are pushed to a stack and executed in
filo order
types
pointers
func main() {
i, j := 42, 2701
p := &i
fmt.Println(*p)
// 42
*p = 21
fmt.Println(i)
// 21
p = &j
*p = *p / 37
fmt.Println(j)
// 73 (2701/37)
}
structs
type Vertex struct {
X int
Y int
}
func main() {
fmt.Println(Vertex{1, 2})
// {1, 2}
}
struct values are accessed using a dot:
Vertex{1, 2}.X
arrays
func main() {
var a [2]string
a[0] = "Hello"
a[1] = "World"
fmt.Println(a[0], a[1])
// Hello World
fmt.Println(a)
// [Hello World]
odd := [4]int{3, 5, 7, 9}
fmt.Println(odd)
// [3, 5, 7, 9]
}
an array has a fixed size
slices
but slices are dynamic!
func main() {
odd := [4]int{3, 5, 7, 9}
var s []int = odd[1:3]
fmt.Println(s)
// [5 7]
}
slices are dynamic references to arrays,
changing a value of a slice will change it in
the array
basics
building and running c
gcc [filename] -o [output] ./[output] ## For example gcc main.c -o out && ./out
basics
introduction
creating a new rust project
cargo new foo
maths
square root
func Sqrt(x float64) float64 {
z := 1.0
for {
n := (z*z-x) / (2*z)
z -= n
if math.Abs(n) < 1e-10 {
return z
}
}
}
calculating a square root using newton
iterations