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() {
.Println("Bob")
fmt}
Create a program that shows your address
package main
import "fmt"
func main() {
.Println("Street 123, City X, Country Y")
fmt}
Comments
Create a program and add a comment with your name
package main
import "fmt"
func main() {
// comment
.Println("Program")
fmt}
Strings
Create a program with multiple string variables
package main
import "fmt"
func main() {
:= "hello "
s1 := "world"
s2 .Println(s1,s2)
fmt}
Create a program that holds your name in a string.
package main
import "fmt"
func main() {
:= "Bob"
name .Println(name)
fmt}
Keyboard input
Make a program that lets the user input a name
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
:= bufio.NewReader(os.Stdin)
reader
.Print("Enter your name: ")
fmt, _ := reader.ReadString('\n')
name.Print("Hello ", name)
fmt}
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() {
:= bufio.NewReader(os.Stdin)
reader
.Print("Enter a number: ")
fmt, _ := reader.ReadString('\n')
str1
// remove newline
= strings.Replace(str1,"\n","",-1)
str1
// convert string variable to int variable
, e := strconv.Atoi(str1)
numif e != nil {
.Println("conversion error:", str1)
fmt}
if num >= 1 && num <= 10 {
.Println("correct")
fmt} else {
.Println("num not in range")
fmt}
}
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() {
:= 50
p1 := 30
p2 := 20
p3 := 25
p4 := 35
p5
:= (p1+p2+p3+p4+p5) / 5
avg
.Println(avg)
fmt}
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 }
.Println(a)
fmt}
Create an array of strings with names
package main
import (
"fmt"
)
func main() {
var a = []string{ "A","B","C" }
.Println(a)
fmt}
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++ {
.Printf("iteration x: %d\n", x)
fmt}
}
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() {
:= 3.0
x if x > 2 {
= x / 2
x }
.Println(x)
fmt}
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() {
, err := os.Create("file.txt")
file
if err != nil {
return
}
defer file.Close()
var a = []string{ "Rio","New York City","Milano" }
for i := 0; i < len(a); i++ {
.WriteString(a[i])
file.WriteString("\n")
file}
}
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() {
.Seed(time.Now().UnixNano())
rand:= random(1, 7)
randomNum .Printf("Random number: %d\n", randomNum)
fmt}
Can you generate negative numbers?
:= random(-7, 7) randomNum
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() {
:= "hello world"
mystring := mystring[0:5]
hello := mystring[6:11]
world .Println(hello)
fmt.Println(world)
fmt}
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)
.Printf( "Value is : %.2f\n", ret )
fmt}
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 {
.Println(s)
fmt}
}
func main() {
:= []string{ "Alice","Bob","Charley" }
a (a...)
show}
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?
<- "message" c
How can you read data from a channel?
:= <- c msg