quick beginner's guide to Golang
Tags: go, beginners
Published: 2019-07-28 16:40:46

---
title: quick beginner's guide to Golang
published: true
description: 
tags: go, beginners
cover_image: https://proxy.duckduckgo.com/iu/?u=https%3A%2F%2Fwww.hardwinsoftware.com%2Fblog%2Fwp-content%2Fuploads%2F2018%2F02%2Fgolang-gopher.png&f=1.jpg
---


# Go
Go language, or Golang, is a statically-typed, compiled programming language initially developed at Google in 2007. It provides garbage collection, type safety, dynamic-typing capability, and other advanced built-in types such as variable length arrays and key-value maps. 

## format of a typical Go file, `main.go`
```golang
package main // declare package name, this line is mandatory

import "fmt" // import packages

func main(){
    fmt.Println("Hello World")
}  // every Go program has at least one function, which is main().
```

to execute it, run 
`go run main.go`

or `go build` to make an executable file


## variables
method 1:
```golang
func main(){
    var name string = "Mary"
    var age int = 40
}
```

method 2 (type inference):
```golang
func main(){
    name := "Mary"
    age := 40
}
```

## if... else...
```golang
func main(){
    age := 50
    if age > 50 {
        fmt.Println("More than 50")
    } else if age < 50 {
        fmt.Println("Less than 50")
    } else {
        fmt.Println("50 Years Old")
    }
}
```

## arrays
Arrays in Go are fixed-size and can be created like this `var variable_name [SIZE] variable_type`
```golang
func main(){
// declaring arrays
    var a [5] string // ["", "", "", "", ""]
// initializing arrays
    fruits := [5]string{"banana", "orange", "apple", "kiwi", "mango"} 
    // ["banana", "orange", "apple", "kiwi", "mango"]
}
```
## slice
an abstraction over arrays to create dynamically-sized arrays
```golang
func main(){
    ages := []int{10, 20, 35, 40, 50} // [10, 20, 35, 40, 50]
    ages = append(ages, 60) // adds an element. original slice is not modified, a new one is returned
}
```

## maps
Maps hold key-value pairs, much like dictionaries in Python. to create a map, use the built-in 'make' function

```golang
func main(){
    // create map
    ages := make(map[string]int)

    ages["Mary"] = 40
    ages["Pete"] = 30
    ages["Nick"] = 25

   // to delete something from map, use delete function
   delete(ages, "Pete")
}
```


## loops
the only type of loop in Golang is the 'for' loop

```golang
func main(){
    for i := 0; i < 5; i++ {
        fmt.Println(i)
    }   

    // using a 'while loop' style
    j := 0

    for j < 5 {
       fmt.Println(j)
       j++
   }

    // printing items in an array using range
    fruits := []string{"banana", "orange", "grape"}

    for index, value := range fruits {
        fmt.Println("index:", index, "value:", value)
        /* index: 0 value: banana
           index: 1 value: orange
           index: 2 value: grape */               
    }

    // printing items in a map using range
    ages := make(map[string]int)

    ages["Mary"] = 40
    ages["Pete"] = 30
    ages["Nick"] = 25

    for key, value := range fruits {
        fmt.Println("name:", key, "age:", value)
        /* name: Mary age: 40
           name: Pete age: 30
           name: Nick age: 35 */               
    }
}
```

## functions 
```golang
func main(){
    result := sum(10, 5)
    fmt.Println(result) // 15
}

// simple function, return type is specified after parameter list
func sum(int a, int b) int {
    return a + b
}
```

a Go function can return multiple types. this can be useful for error handling as Go doesn't have exceptions like other languages.
```golang
import (
    "fmt"
    "errors"
    "math"
)

func main(){
    result, err := sqrt(4)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(result)
    }
}

func sqrt(x float64) (float64, error) {
    if x < 0 {
        return 0, errors.New("Undefined for negative number")
    }
    return math.Sqrt(x), nil
}
```
## struct
a struct is a collection of fields so that you can group things together to create a more logical type.

```golang
type person struct {
    name string
    age int
}

func main(){
    p := person{name: "Nick", age: "25"}

    // use dot notation to access a member of a struct
    fmt.Println(p.age) // 25
}
```

## pointers
Every variable is stored in memory and we can get the memory address of the variable by using the ampersand (&) operator.

```golang
func main(){
    i := 10
    fmt.Println(&i) // prints memory address
    inc(i)
    fmt.Println(i) // 10
    
}

func inc(x int) {
    x++
}
``` 

in the above example, the `inc` function is not going to do anything because `i` is copied by value so the `inc` function gets a copy of `i` and the original version is not modified.

however, if we pass a pointer to the variable then the function is able to look at the value at that memory reference and modify the original version.

we can accept a pointer by prefixing the type with an asterisk (*) and send the pointer using an ampersand (&). inside the `inc` function, we need to add another asterisk to dereference the pointer

```golang
func main(){
    i := 10
    inc(&i)
    fmt.Println(i) // 11
    
}

func inc(x *int) {
    *x++
}
```