These are answers to the questions shown at golangr.com. They are part of the Go (golang) programming tutorial.

Its recommended to try the exercises before, instead of overlooking the answers. That is because programming is learned by trial and error, practice.

Hello world

Create a program that shows your name

package main

import "fmt"

func main() {
fmt.Println("Bob")
}

Create a program that shows your address

package main

import "fmt"

func main() {
fmt.Println("Street 123, City X, Country Y")
}

Comments

Create a program and add a comment with your name

package main

import "fmt"

func main() {
    // comment
    fmt.Println("Program")
}

Strings

Create a program with multiple string variables

package main

import "fmt"

func main() {
    s1 := "hello "
    s2 := "world"
    fmt.Println(s1,s2)
}

Create a program that holds your name in a string.

package main

import "fmt"

func main() {
    name := "Bob"
    fmt.Println(name)
}

Keyboard input

Make a program that lets the user input a name

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    reader := bufio.NewReader(os.Stdin)

    fmt.Print("Enter your name: ")
    name, _ := reader.ReadString('\n')
    fmt.Print("Hello ", name)
}

Get a number from the console and check if it’s between 1 and 10.

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    reader := bufio.NewReader(os.Stdin)

    fmt.Print("Enter a number: ")
    str1, _ := reader.ReadString('\n')

    // remove newline
    str1 = strings.Replace(str1,"\n","",-1)

    // convert string variable to int variable
    num, e := strconv.Atoi(str1)
    if e != nil {
    fmt.Println("conversion error:", str1)
    }

    if num >= 1 && num <= 10 {
    fmt.Println("correct")
    } else {
        fmt.Println("num not in range")
    }
}

Variables

Calculate the year given the date of birth and age Create a program that calculates the average weight of 5 people.

package main

import (
    "fmt"
)

func main() {
    p1 := 50
    p2 := 30
    p3 := 20
    p4 := 25
    p5 := 35

    avg := (p1+p2+p3+p4+p5) / 5

    fmt.Println(avg)
}

Scope

What’s the difference between a local and global variable?

Where the variable can be used in the code. A global variable can be used in the entire code file. A local variable only in a function, loop or section.

How can you make a global variable?

Define it on top of the file

Arrays

Create an array with the number 0 to 10

package main

import (
    "fmt"
)

func main() {
    var a = []int64{ 1,2,3,4,5,6,7,8,9,10 }
    fmt.Println(a)
}

Create an array of strings with names

package main

import (
    "fmt"
)

func main() {
    var a = []string{ "A","B","C" }
    fmt.Println(a)
}

For loops

Can for loops exist inside for loops?

Yes they can. That’s called nested loops.

Make a program that counts from 1 to 10.

package main

import "fmt"

func main() {
   for x := 1; x <= 10; x++ {
        fmt.Printf("iteration x: %d\n", x)
   }
}

Range

What is the purpose of range ?

To iterate over all the elements of a data structure, array, slice and others.

What the difference between the line for index, element := range a and the line for _, element := range a ?

index holds the position of the element in the data structure. Sometimes you may not need it, then you can use underscore.

If statements

Make a program that divides x by 2 if it’s greater than 0

package main

import "fmt"

func main() {
    x := 3.0
    if x > 2 {
        x = x / 2
    }
    fmt.Println(x)
}

Find out if if-statements can be used inside if-statements.

Yes, that’s called nested-if.

While loops

How does a while loop differ from a for loop?

A for loop has a predefined amount of iterations. A while loop doesn’t necessarily.

Files

Read file

Think of when you’d read a file ‘line by line’ vs ‘at once’?

If you have a very large file, line by line is better because otherwise it won’t fit into memory.

Create a new file containing names and read it into an array

See article

Write file

Write a list of cities to a new file.

package main

import "os"

func main() {
    file, err := os.Create("file.txt")

    if err != nil {
        return
    }
    defer file.Close()

    var a = []string{ "Rio","New York City","Milano" }
    for i := 0; i < len(a); i++ {
        file.WriteString(a[i])
        file.WriteString("\n")
    }
}

Rename file

Which package has the rename function?

os

Struct

How does a struct differ from a class?

Classes are a concept of object oriented programming. A class can be used to create objects. Classes can inherit from another.

Maps

What is a map?

A Golang map is a unordered collection of key-value pairs.

Is a map ordered?

No

What can you use a map for?

To store key value pairs

Random numbers

Make a program that rolls a dice (1 to 6)

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func random(min int, max int) int {
    return rand.Intn(max-min) + min
}

func main() {
    rand.Seed(time.Now().UnixNano())
    randomNum := random(1, 7)
    fmt.Printf("Random number: %d\n", randomNum)
}

Can you generate negative numbers?

randomNum := random(-7, 7)

Pointers

Where are variables stored in the computer?

Memory

What is a pointer?

A pointer is a variable whose address is the direct memory address of another variable.

How can you declare a pointer?

Use the asterisk *, var var_name *var-type.

Slices

Take the string ‘hello world’ and slice it in two.

package main

import "fmt"

func main() {
    mystring := "hello world"
    hello := mystring[0:5]
    world := mystring[6:11]
    fmt.Println(hello)
    fmt.Println(world)
}

Can you take a slice of a slice?

Yes

Methods

Create a method that sums two numbers

package main

import "fmt"

func main() {
   var a float64 = 3
   var b float64 = 9
   var ret = sum(a, b)
   fmt.Printf( "Value is : %.2f\n", ret )
}

func sum(num1, num2 float64) float64 {
   return num1+num2
}

Create a method that calls another method.

See above main() calls sum().

Multiple return

Can a combination of strings and numbers be used?

Yes

Variadic functions

Create a variadic function that prints the names of students

package main

import "fmt"

func show(students ...string) {
    for _, s := range students {
        fmt.Println(s)
    }
}

func main() {
    a := []string{ "Alice","Bob","Charley" }
    show(a...)
}

Recursion

When is a function recursive?

A function is recursive if it:

Calls itself
Reaches the stop condition

Can a recursive function call non-recursive functions?

Yes, it can

Goroutines

What is a goroutine?

A goroutine is a function that can run concurrently.

How can you turn a function into a goroutine?

Write go before the function call

Concurrency

What is concurrency?

Concurrency, do lots of things at once. That’s different from doing lots of things at the same time

Channels

When do you need channels?

To communicate between goroutines

How can you send data into a channel?

c <- "message"

How can you read data from a channel?

msg := <- c