DEV Community

Cover image for quick beginner's guide to Golang
delph
delph

Posted on

quick beginner's guide to Golang

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

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:

func main(){
    var name string = "Mary"
    var age int = 40
}

method 2 (type inference):

func main(){
    name := "Mary"
    age := 40
}

if... else...

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

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

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

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

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

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.

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.

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.

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

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

}

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

Top comments (0)