Golang Quick Notes

Assignments

Assignment operator: = perform assignments; assign or reassign values to already declared variables
Short declaration operator := perform short variable declarations; shorthand for regular variable declarations but without a specified type

Switch statement

– use commas to separate cases

switch time.Now().Weekday() {
    case time.Saturday, time.Sunday:

– deafult case is optional

default:
        fmt.Println("It's a weekday")

Variadic Functions

func sum(nums ...int) {
for _, num := range nums {
// ...
}
}
func main() {
sum(1, 2)
sum(1, 2, 3)
nums := []int{1, 2, 3, 4}
sum(nums...)
}

Anonymous Function = Closure = Function Literal

func intSeq() func() int {
i := 0
return func() int {
i++
return i
}
}

You can assign AF to a variable

value := func(){
fmt.Println("Welcome! to GeeksforGeeks")
}

Pointers and references

In Go you can work with values or pointers.
This function accepts a value:

func valueParam(ival int) {
ival = 0
}

This function accepts a pointer:

func pointerParam(iptr *int) {
*iptr = 0
}

Pointer provides an address to the value. Assigning a value to a dereferenced pointer changes the value at the referenced address.

func main() {
i := 1
fmt.Println("initial:", i)
valueParam(i)
fmt.Println("valueParam:", i)
pointerParam(&i)
fmt.Println("pointerParam:", i)
fmt.Println("pointer:", &i)
}
initial: 1
zeroval: 1
zeroptr: 0
pointer: 0x42131100

The &i syntax gives the memory address of i, i.e. a pointer to i.
Pointers can be printed too.