Go Basics
Variables
Strictly Typed and Compiled
1var a bool
2a = false
3b := true
4
5fmt.Println(a, "and", b) // false and true
1type banana int
2var b banana
3fmt.Println(b)
4// 0
5fmt.Printf("%T\n", b)
6// main.banana
Functions
function singature func functionname(parametername type) returntype {
1func addNum(a int, b int) int {
2 var sum = a + b
3 return sum
4}
hello world
1package main
2
3import (
4 "fmt"
5)
6
7func main() {
8 fmt.Printf("Hello, Chris.\n")
9}
Composite Data Types
Arrays
Arrays are fixed length
ArrayType = [length]ElementType
1var list [5]int
2fmt.Println(list)
3// [0 0 0 0 0]
Slices
Numbered lists of a single type. They can be resized. Slices are built on top of arrays and passed by reference
Composite literal syntax t := type{values}
1listX := []int{1, 2, 5, 8}
2fmt.Println(listX)
3// [1 2 5 8]
Iterate through slice
1// range allows looping through slices
2// (as well as arrays, maps, strings,
3// and reading from channels)
4for index, value := range listX {
5 fmt.Println(index, value)
6}
7//0 1
8//1 2
9//2 5
10//3 8
Working with Slices
Make function will create a new slice
1var listY = make([]string, 3, 5)
Shorthand for creating a new slice and iterating through it
1for i, v := range []string{"foo", "bar", "baz"} {
2 listY[i] = v
3}
Append items to slice.
1listOdd := []int{1, 3, 5, 7, 8}
2listOdd = append(listOdd, 9, 11, 13, 15)
3fmt.Println(listOdd)
4
5newOddNumbers := []int{17, 19, 21}
6listOdd = append(listOdd, newOddNumbers...)
...
will unfurl a list. It is useful for passing in variadic parameters from list data types (like above.)
Slicing a slice
1fmt.Println(listOdd[0])
2// 1
3fmt.Println(listOdd[1])
4// 2
5fmt.Println(listOdd[2:5])
6// [5 7 8]
7// From the beginning to the specified index
8fmt.Println(listOdd[:5])
9// [1 3 5 7 8]
10// From the specified index to the end
11fmt.Println(listOdd[5:])
12// [9 11 13 15 17 19 21]
Deleting from a slice
1// Deleting element from slice.
2listOdd = append(listOdd, 22, 24, 23, 25)
3fmt.Println(listOdd)
4// [1 3 5 7 8 9 11 13 15 17 19 21 22 24 23 25]
5realOdd := append(listOdd[:12], listOdd[14:]...)
6fmt.Println(realOdd)
7// [1 3 5 7 8 9 11 13 15 17 19 21]