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.

Related course: Introducing Go: Build Reliable, Scalable Programs

Hello world

Create a program that shows your name

1
2
3
4
5
6
7
package main

import "fmt"

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

Create a program that shows your address

1
2
3
4
5
6
7
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

1
2
3
4
5
6
7
8
package main

import "fmt"

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

Strings

Create a program with multiple string variables

1
2
3
4
5
6
7
8
9
package main

import "fmt"

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

Create a program that holds your name in a string.

1
2
3
4
5
6
7
8
package main

import "fmt"

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

Keyboard input

Make a program that lets the user input a name

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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

1
2
3
4
5
6
7
8
9
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

1
2
3
4
5
6
7
8
9
10
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.

1
2
3
4
5
6
7
8
9
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

1
2
3
4
5
6
7
8
9
10
11
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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?

1
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.

1
2
3
4
5
6
7
8
9
10
11
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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?

1
c <- "message"

How can you read data from a channel?

1
msg := <- c