The Way to Go Educative Quiz Answers

Get The Way to Go Educative Quiz Answers

Go (sometimes called Golang) is one of the most popular languages today, and is a key part of many enterprise tech stacks. Many developers prefer Go to other languages like C++ and Scala because of its memory management model which allows for easier concurrency.

In this course, you will learn the core constructs and techniques of the language. After going through the basics, you will then learn more advanced Go concepts like error-handling, networking, and templating. You’ll learn how to program efficiently in Go by gaining knowledge of common pitfalls and patterns, as well as by building your own applications.

Enroll on Educative

Quiz 1: Test Yourself

Q1. Which of the following are features of Golang?

  • Easy to learn and use
  • Fast compilation
  • Static typing
  • Consistent standard library
  • All of the above

Q2. Which features are missing from Go?

  • Functions
  • Operators overloading
  • Mutable variables
  • All of the above

Q3. Which of the following statements is False?

  • Golang is free and open sourced (BSD licensed).
  • Golang includes all the features of modern OOP languages.
  • None of the above

Quiz 2: Basic Constructs and Elementary Data Types

Q1. Deduce the output of the following program.

package main
var a = "G"
func main() {
   n()

   m()
   n()
}
func n() { print(a) }
func m() {
  a := "O"
  print(a)
}
  • OGO
  • GOG
  • GOO
  • OGG

Q2. Deduce the output of the following program.

package main
var a = "G"
func main() {
  n()
  m()
  n()
}
func n() {
    print(a)
}
func m() {
  a = "O"
  print(a)
}
  • OGO
  • GOG
  • GOO
  • OGG

Q3. Deduce the output of the following program.

package main
var a string
func main() {
  a = "G"
  print(a)
  f1()
}
func f1() {
  a := "O"
  print(a)
    f2()
}
func f2() {
    print(a)
}
  • GOG
  • OGO
  • OGG
  • GOO

Quiz 3: Control Structures

Q1. What will the following function return for x=2 and y=5?

func isGreater(x, y int) bool {
  if x > y {
    return true
  }
    return false
}
  • True
  • False
  • None of the above

Q2. What will the following function return for x=-10?

func Abs(x int) int {
  if x < 0 {
    return -x
  }
    return x
}
  • -10
  • 10
  • 1

Q3. What will the following program generate as an output?

package main
import "fmt"

func main() {
  if val := 10; val > 100 {
    // do something
  }
  fmt.Printf("The value of val is %d\n", val)
}
  • The value of val is 10
  • The value of val is %d\n 10
  • Compiler Error: undefined: val

Q4. What will the following program generate as an output?

package main
import "fmt"

func main() {
  val := 42
  if val := 10; val > 5 {
    fmt.Printf("The value of val is %d\n", val)
  }
  fmt.Printf("The value of val is %d\n", val)
}
  • The value of val is 10
    The value of val is 42
  • The value of val is 10
    The value of val is 10
  • The value of val is 42
    The value of val is 42
  • The value of val is 42 The value of val is 10

Q5. What is the output of the following code snippet?

k := 6
switch k {
  case 4: fmt.Println("was <= 4"); fallthrough;
  case 5: fmt.Println("was <= 5"); fallthrough;
  case 6: fmt.Println("was <= 6"); fallthrough;
  case 7: fmt.Println("was <= 7"); fallthrough;
  case 8: fmt.Println("was <= 8"); fallthrough;
  default: fmt.Println("default case")
}
  • was <= 4
    was <= 5
    was <= 6
    was <= 7
    was <= 8
    default case
  • was <= 6
    was <= 7
    was <= 8
    default case
  • was <= 4
    was <= 5
    was <= 6
    was <= 7
    was <= 8
  • was <= 6
    was <= 7
    was <= 8

Q6. What is the output of the following Go Program?

package main
import "fmt"
func main() {
  for i:=0; i<10; i++ {
    fmt.Printf("%v\n", i)
  }
  fmt.Printf("%v\n", i)
}
  • 0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    9
  • 0
    1
    2
    3
    4
    5
    6
    7
    8
    9
  • Compile error: undefined:i

Q7. What will this loop print out?

for i := 0; i < 5; i++ {
  var v int
  fmt.Printf("%d ", v)
  v = 5
}
  • 0 0 0 0 0
  • 0 5 5 5 5
  • 0 0 0 0 0 0
  • 0 5 5 5 5 5

Q8. Which of the following is an infinite loop?

  • Code 1
for i := 0; ; i++ {

    fmt.Println("Value of i is now:", i)

}
  • Code 2
for i := 0; i < 3; {

fmt.Println("Value of i:", i)

}
  • All of the above

Q9. What will this loop print out?

s := ""
for ; s != "aaaaa"; {

  fmt.Println("Value of s:", s)
  s = s + "a"

}
  • Value of s: a
    Value of s: aa
    Value of s: aaa
    Value of s: aaaa
  • Value of s:a
    Value of s: aa
    Value of s: aaa
    Value of s: aaaa
    Value of s: aaaaa
  • Value of s:
    Value of s: a
    Value of s: aa
    Value of s: aaa
    Value of s: aaaa
  • None of the above

Q10. What will this loop print out?

for i, j, s := 0, 5, "a"; i < 3 && j < 100 && s != "aaaaa"; i, j, s = i+1, j+1, s+ "a" {

    fmt.Println("Value of i, j, s:", i, j, s)
}
  • Value of i, j, s: 0 5 a
    Value of i, j, s: 1 6 aa
    Value of i, j, s: 7 2 aaa
  • Value of j, i, s: 0 5 a
    Value of j, i, s: 1 6 aa
    Value of j, i, s: 2 7 aaa
  • Value of i, j, s: 0 5 aaa
    Value of i, j, s: 1 6 aa
    Value of i, j, s: 2 7 a
  • Value of i, j, s: 0 5 a
    Value of i, j, s: 1 6 aa
    Value of i, j, s: 2 7 aaa

Q11. What is the output of the following code?

LOOP:
for i := 0; i < 10; i++ {
  if i == 5 {
    break LOOP
  }
  fmt.Println(i)
}
  • 0
    1
    2
    3
    4
  • 0
    1
    2
    3
    4
    6
    7
    8
    9
  • Infinite loop

Q12. What is the output of the following code?

LOOP:
for i := 0; i < 10; i++ {
  if i == 5 {
    continue LOOP
  }
  fmt.Println(i)
}
  • 0
    1
    2
    3
    4
  • 0
    1
    2
    3
    4
    6
    7
    8
    9
  • Infinite loop

Q13. What will the following loop print out?

LOOP:
for i := 0; i < 10; i++ {
  if i == 5 {
    goto LOOP
  }
  fmt.Println(i)
}
  • 0
    1
    2
    3
    4
  • 0
    1
    2
    3
    4
    5
    6
    7
    8
    9
  • Infinite loop

Q14. What will the following loop print out?

i := 0
for {
  if i >= 3 { break }
  fmt.Println("Value of i is:", i)
  i++;
}
fmt.Println("A statement just after for loop.")
  • Value of i is: 0
    Value of i is: 1
    Value of i is: 2
    Value of i is: 3
    A statement just after for loop.
  • Infinite loop
  • Value of i is: 0
    Value of i is: 1
    Value of i is: 2
    A statement just after for loop.

Q15. What will the following loop print out?

for i := 0; i<7 ; i++ {
    if i%2 == 0 { continue }
    fmt.Println("Odd:", i)
}
  • Odd: 1
    Odd: 3
    Odd: 5
  • Infinite loop
  • Odd: 0
    Odd: 2
    Odd: 4
  • None of the above

Quiz 4: Functions

Q1. Which of the following is the true statement?

func DoSomething1(a *A) {
    b = a
}
func DoSomething2(a A) {
    b = &a
}
  • DoSomething1 assigns b the value present at a.
  • DoSomething1 assigns b the adress the same as a.
  • DoSomething2 assigns b the adress the same as a.
  • Both A and C
  • Both B and C

Q2. What is/are the return value(s) of the following function MySqrt for f equals to -2?

func MySqrt(f float64)(float64, error) {
    //return an error as second parameter if invalid input
    if (f < 0) {
        return float64(math.NaN()), errors.New("I won't be able to do a sqrt of negative number!")
    }
    //otherwise use default square root function
    return math.Sqrt(f), nil
}
  • NaN I won’t be able to do a sqrt of negative number!
  • NaN
  • 1.4142135623730951
  • None of the above
  • Both B and C

Q3. What will the return values(s) of the following task for a equals 78 and b equals 65 be?

func task(a int, b int)(m int, n int) {
    if a < b {
        m = a
        n = b
    } else { 
        m = b
        n = a
    }
    return
}
  • 78, 65
  • 65, 78
  • 78
  • 65

Q4. What will the return value(s) of the following function task for task(7,9,3,5,1) be?

func task(a...int) int {
    if len(a) == 0 {
        return 0
    }
    value := a[0]
    for _, v := range a {
        if v < value {
            value = v
        }
    }
    return value
}
  • 5
  • 9
  • 7
  • 1

Q5. What is the output of the following Go program?

package main
import "fmt"
func trace(s string) string {
    fmt.Println("entering:", s)
    return s
}
func un(s string) {
    fmt.Println("leaving:", s)
}
func a() {
    defer un(trace("a"))
    fmt.Println("in a")
}
func b() {
    defer un(trace("b"))
    fmt.Println("in b")
    a()
}
func main() {
    b()
}
  • entering: b
    in b
    leaving: b
    entering: a
    in a
    leaving: a
  • entering: b
    leaving: b
    in b
    entering: a
    leaving: a
    in a
  • entering: b
    in b
    entering: a
    in a
    leaving: a
    leaving: b
  • entering: a
    in a
    entering: b
    in b
    leaving: b
    leaving: a

Q6. What is the output of the following Go program?

package main
import "fmt"

func main() {
    printrec(1)
}

func printrec(i int) {
    if i > 10 {
        return
    }
    printrec(i + 1)
    fmt.Printf("%d ", i)
}
  • 10 9 8 7 6 5 4 3 2 1
  • 1 2 3 4 5 6 7 8 9 10
  • Compiler Error
  • None of the Above

Q7. What is the output of the following program?

package main
import "fmt"
func f()(ret int) {
    defer func() {
        ret++
    }()
    return 1
}
func main() {
    fmt.Println(f())
}
  • 1
  • 2
  • 3
  • None of the Above

Q8. What is the output of the following Go program?

package main
import (
    "fmt"
    "math"
)

func Compose(f, g float64) func(x float64) float64 {
    return func(x float64) float64 { // closure
        return math.Pow(math.Pow(f,g),x)
    }
}

func main() {
    fmt.Print(Compose(4,2)(3)) 
}
  • 144
  • 6561
  • 4096
  • None of the Above

Quiz 5: Arrays and Slices

Q1. What is the output of the following code snippet?

a := [...]string{"a", "b", "c", "d"}

for i := range a {
    fmt.Println("Array item", i, "is", a[i])
}
  • Array item 0 is a
    Array item 1 is b
    Array item 2 is c
  • Array item 0 is a
    Array item 1 is b
    Array item 2 is c
    Array item 3 is d
  • Compiler error
  • None of the above

Q2. What is the output of the following Go program?

package main
import "fmt"

func main() {
    var arrKeyValue = [5]string{3: "Chris", 4: "Ron"}

  for i := 0; i < len(arrKeyValue); i++ {
    fmt.Printf("Person at index %d is %s\n", i, arrKeyValue[i])
  }
}
  • Person at index 1 is
    Person at index 2 is
    Person at index 3 is Chris
    Person at index 4 is Ron
    Person at index 5 is
  • Person at index 0 is Chris
    Person at index 1 is Ron
    Person at index 2 is
    Person at index 3 is
    Person at index 4 is
  • Person at index 0 is
    Person at index 1 is
    Person at index 2 is
    Person at index 3 is Chris
    Person at index 4 is Ron
  • None of the above

Q3. What is the output of the following Go program?

package main
import "fmt"

func fp(a *[3]int) { fmt.Println(a) }

func main() {
  for i := 0; i < 3; i++ {
    fp(&[3]int{i, i * i, i * i * i}) // newly created instance
  }
}
  • &[0 0 0]
    &[1 1 1]
    &[2 4 8]
  • [0 0 0]
    [1 1 1]
    [2 4 8]
  • &[0 0 0]
    &[1 2 3]
    &[2 4 6]
  • [0 0 0]
    [1 2 3]
    [2 4 6]

Q4. Given the slice of bytes:

b := []byte{'g', 'o', 'l', 'a', 'n', 'g'}

What are the length and capacity of: b[1:4] , b[:2]b[2:] and b[:] ?

  • Length and capacity of b[1:4] is 4 and 5 respectively.
    Length and capacity of b[:2] is 3 and 6 respectively.
    Length and capacity of b[2:] is 2 and 4 respectively.
    Length and capacity of b[:] is 6 and 6 respectively.
  • Length and capacity of b[1:4] is 3 and 2 respectively.
    Length and capacity of b[:2] is 2 and 4 respectively.
    Length and capacity of b[2:] is 4 and 2 respectively.
    Length and capacity of b[:] is 6 and 0 respectively.
  • Length and capacity of b[1:4] is 3 and 5 respectively.
    Length and capacity of b[:2] is 2 and 6 respectively.
    Length and capacity of b[2:] is 4 and 2 respectively.
    Length and capacity of b[:] is 6 and 0 respectively.
  • Length and capacity of b[1:4] is 3 and 5 respectively.
    Length and capacity of 
    b[:2] is 2 and 6 respectively.
    Length and capacity of 
    b[2:] is 4 and 4 respectively.
    Length and capacity of 
    b[:] is 6 and 6 respectively.

Q5. For the following code:

s := make([]byte, 5)    // line 1
s = s[2:4]                      // line 2

What are len(s) and cap(s) at line 1 and line 2 ?

  • Line 1: Length and capacity of s are 4 and 4.
    Line 2: Length and capacity of s are 2 and 3.
  • Line 1: Length and capacity of s are 5 and 5.
    Line 2: Length and capacity of 
    s are 2 and 3.
  • Line 1: Length and capacity of s are 5 and 5.
    Line 2: Length and capacity of s are 3 and 2.
  • Line 1: Length and capacity of s are 4 and 4.
    Line 2: Length and capacity of s are 3 and 2.

Q6. According to the following code snippet:

s1 := []byte{'p', 'o', 'e', 'm'}
s2 := s1[2:]    // line 2
s2[1] = 't'     // line 3

What is the value of s2 at line 2 and line 3?

  • Line 2: s2 = {‘e’,‘m’}
    Line 3: 
    s2 = {‘e’,‘t’}
  • Line 2: s2 = {‘p’,‘o’}
    Line 3: s2 = {‘p’,‘t’}
  • Line 2: s2 = {‘o’,‘e’,‘m’}
    Line 3: s2 = {‘o’,‘t’,‘m’}
  • None of the above

Q7. Suppose we have the following slice:

items := [...]int{10, 20, 30, 40, 50}

If we code the following for-loop, what will be the value of items after the loop ?

for _, item := range items {
item *= 2
}
  • {10, 20, 30, 40, 50}
  • {20, 40, 60, 80, 100}
  • Compiler Error
  • None of the above

Q8. If s is a slice, what is the length of s[n:n] and s[n:n+1] ?

  • length of s[n:n] is 1.
    length of s[n:n+1] is 2.
  • length of s[n:n] is 4.
    length of s[n:n+1] is 5.
  • length of s[n:n] is 3.
    length of s[n:n+1] is 4.
  • length of s[n:n] is 0.
    length of 
    s[n:n+1] is 1.

Q9. If str is a string, what is the value of str[len(str)/2:] + str[:len(str)/2] ? Test it out for str equals to Google.

  • gleGoo
  • Google
  • ooGelg
  • elgooG

Q10. What is the output of the following program?

package main
import "fmt"

func main() {
    str := "Google"
    for i:=0; i <= len(str); i++ {
        a, b := Split(str, i)
        fmt.Printf("The string %s split at position %d is: %s / %s\n", str, i, a, b)
    }
}

func Split(s string, pos int) (string, string) {
    return s[0:pos], s[pos:]
}
  • The string Google split at position 0 is: G / oogle
    The string Google split at position 1 is: Go / ogle
    The string Google split at position 2 is: Goo / gle
    The string Google split at position 3 is: Goog / le
    The string Google split at position 4 is: Googl / e
    The string Google split at position 5 is: Google /
  • The string Google split at position 0 is: /
    The string Google split at position 1 is: G / oogle
    The string Google split at position 2 is: Go / ogle
    The string Google split at position 3 is: Goo / gle
    The string Google split at position 4 is: Goog / le
    The string Google split at position 5 is: Googl / e
    The string Google split at position 6 is: Google /
  • The string Google split at position 0 is: / Google
    The string Google split at position 1 is: G / oogle
    The string Google split at position 2 is: Go / ogle
    The string Google split at position 3 is: Goo / gle
    The string Google split at position 4 is: Goog / le
    The string Google split at position 5 is: Googl / e
    The string Google split at position 6 is: Google /
  • None of the above

Q11. What will the following function task return for the slice {“M”, “N”, “O”, “P”, “Q”, “R”}index1 as 2 and index2 as 4?

func task(slice []string, index1, index2 int) []string {
    result := make([]string, len(slice) - (index2 - index1))
    at := copy(result, slice[:index1])
    copy(result[at:], slice[index2:])
    return result
}
  • {M N Q R}
  • {O P}
  • {N M R Q}
  • {P O}

Q12. What do the following two functions task1 and task2 return for sl equals to {78, 34, 643, 12, 90, 492, 13, 2}?

func task1(sl []int) (n int) {
    n = math.MinInt32
    for _, v := range sl {
        if v > n {
            n = v
        }
    }
    return 
}

func task2(sl [] int) (n int) { 
    n = math.MaxInt32  
    for _, v := range sl {
        if v < n {
            n = v
        }
    }
    return 
}
  • Compiler Error
  • task1 returns 2 and task2 returns 643.
  • task2 returns 2 and task1 returns 643.
  • None of the above

Quiz 6: Maps

Q1. What is the output of the following code snippet?

capitals := map[string] string {"France":"Paris", "Italy":"Rome", "Japan":"Tokyo" }
fmt.Println(capitals["Tokyo"])
fmt.Println(capitals["Italy"])
fmt.Println(capitals["Paris"])
  • Rome
  • Japan
    France
  • Compiler Error
  • Japan
    Rome
    France

Q2. What is the output of the following code snippet?

capitals := map[string] string {"France":"Paris", "Italy":"Rome", "Japan":"Tokyo" }
for key := range capitals {
    fmt.Println("Map item: Capital of", key, "is", capitals[key])
}
  • Map item: Capital of France is Paris
    Map item: Capital of Italy is Rome
    Map item: Capital of Japan is Tokyo
  • Map item: Capital of Italy is Rome
    Map item: Capital of Japan is Tokyo
    Map item: Capital of France is Paris
  • Map item: Capital of Rome is Italy
    Map item: Capital of Tokyo is Japan
    Map item: Capital of Paris is France
  • Both A and B

Q3. Which statement is true for the following code snippet?

capitals := map[string] int {"France":0, "Italy":1, "Japan":2 }
val, isPresent := capitals["France"]
  • The value for val is 0, because France key doesn’t exist.
  • The value for val is 0, because France key is associated with 0 at time of declaration.
  • The value for isPresent is false.
  • Both B and C

Q4. What is the output of the following code snippet?

drinks := map[string]string{
    "beer": "bière",
    "wine": "vin",
    "water": "eau",
    "coffee": "café",
    "thea": "thé"}
sdrinks := make([]string, len(drinks))
ix := 0
for eng := range drinks {
    sdrinks[ix] = eng
    ix++
}
sort.Strings(sdrinks)
for _, eng := range sdrinks {
        fmt.Println(eng,":",drinks[eng])
}
  • beer : bière
    coffee : café
    thea : thé
    water : eau
    wine : vin
  • beer : bière
    coffee : café
    thea : thé
    wine : vin
    water : eau
  • wine : vin
    water : eau
    thea : thé
    coffee : café
    beer : bière
  • None of the above

Quiz 7: Structs and Methods

Q1. What’s wrong with the following code?

package main
import "container/list"

func (p *list.List) Iter() {
    // ...
}
func main() {
  lst := new(list.List)
  for _ = range lst.Iter() {
  }
}
  • lst is not a pointer type object
  • Cannot define new methods on non-local type list.List
  • lst.Iter undefined (type *list.List has no field or method Iter)
  • Both B and C
  • All of the above

Q2. Predict the output of the following program:

package main
import "fmt"

type Base struct{}

func (Base) Magic() { fmt.Print("base magic ") }

func (self Base) MoreMagic() {
    self.Magic()
    self.Magic()
}

type Voodoo struct {
    Base
}

func (Voodoo) Magic() { fmt.Println("voodoo magic") }

func main() {
  v := new(Voodoo)
  v.Magic()
  v.MoreMagic()
 }
  • base magic base magic
    voodoo magic
  • voodoo magic
    base magic base magic
  • base magic
    voodoo magic base magic
  • base magic
    voodoo magic voodoo magic

Q3. Predict the output of the following program:

package main
import "fmt"

type Base struct {
    id  string
}

func (b *Base) Id() string {
    return b.id
}

func (b *Base) SetId(id string) {
    b.id = id
}

type Person struct {
    Base
    FirstName       string
    LastName        string
}

type Employee struct {
    Person
    salary      float32


func main() {
    idjb := Base{"007"}
    jb := Person{idjb, "James", "Bond"}
    e := &Employee{jb, 100000.}
    fmt.Printf("ID of our hero: %v\n", e.Id())
    // Change the id:
    e.SetId("007B")
    fmt.Printf("The new ID of our hero: %v\n", e.Id())
}
  • ID of our hero: 007
    The new ID of our hero: 007B
  • ID of our hero: 007
    The new ID of our hero: 007
  • Compiler Error
  • None of the above

Q4. Predict the output of the following program:

package main

import "fmt"

type T struct {
    a int
    b float32
    c string
}

func main() {
    t := &T{ 7, -2.35, "abc\tdef" }
    fmt.Printf("%v\n", t)
}

func (t *T) String() string {
    return fmt.Sprintf("%d / %f / %q", t.a, t.b, t.c)
}
  • 7 / -2.350000 / string “abc\tdef”
  • 7 / -2.35000 / “abc\tdef”
  • 7 / -2.350000 / “abc\tdef”
  • None of the above

Q5. Deduce the output of the following program:

package main
import (
    "fmt"
    "strconv"
)

type Celsius float64

func (c Celsius) String() string {
    return "The temperature is: " +  strconv.FormatFloat(float64(c),'f', 1, 32) + " °C"
}

func main() {
    var c Celsius = 18.36
    fmt.Println(c)
}
  • The temperature is: 18.4 °
  • The temperature is: 18.3 °C
  • The temperature is: 18.36 °C
  • The temperature is: 18 °C

Q6. Predict the output of the following program:

package main
import "fmt"

type TZ int

const (
    HOUR TZ = 60 * 60
    UTC  TZ = 0 * HOUR
    EST  TZ = -5 * HOUR
    CST  TZ = -6 * HOUR  
)

var timeZones = map[TZ]string { 
                                    UTC:"Universal Greenwich time", 
                                EST:"Eastern Standard time",
                                    CST:"Central Standard time", 
                                }

func (tz TZ) String() string { 
    for name, zone := range timeZones {
        if tz == name {
            return zone
        }
    }
    return ""
}

func main() {
    fmt.Println(EST)          // Print knows about method String() of type TZ
    fmt.Println(0 * HOUR)
    fmt.Println(-6 * HOUR)   
}
  • EST
    UTC
    CST
  • Eastern Standard time
    Universal Greenwich time
    Central Standard time
  • Compiler Error
  • None of the above

Quiz 8: Interfaces and Reflection

Q1. Deduce the output of the following program:

package main
import "fmt"

type Any interface {}
type Anything struct {}

func main() {
    any := getAny()
    if any == nil {
        fmt.Println("any is nil")
    } else {
        fmt.Println("any is not nil")
    }
}

func getAny() Any {
    return getAnything()
}
func getAnything() *Anything {
    return nil
}
  • any is nil
  • any is not nil
  • Compiler Error
  • any is nil any is not nil

Q2. Deduce the output of the following program:

package main
import "fmt"

type Any interface {}
type Anything struct {}

func main() {
    any := getAnything()
    if any == nil {
        fmt.Println("any is nil")
    } else {
        fmt.Println("any is not nil")
    }
}

func getAny() Any {
    return getAnything()
}
func getAnything() *Anything {
    return nil
}
  • any is nil
  • any is not nil
  • Compiler Error
  • any is nil any is not nil

Q3. Deduce the output of the following program:

package main
import "fmt"

type obj interface{}

func main() {
    mf := func(i obj) obj {
        switch i.(type) {
            case int:
                return i.(int) * 2
            case string:
                return i.(string) + i.(string)
        }
        return i
    }
    
    isl := []obj{0, 1, 2, 3, 4, 5}
    res1 := mapFunc(mf, isl)
    for _, v := range res1 {
        fmt.Println(v)
    }
    fmt.Println()
    
    ssl := []obj{"0", "1", "2", "3", "4", "5"}
    res2 := mapFunc(mf, ssl)
    for _, v := range res2 {
        fmt.Println(v)
    }
}

func mapFunc(mf func(obj) obj, list []obj) ([]obj) {
    result := make([]obj, len(list))
    
    for ix, v := range list {
        result[ix] = mf(v)
    }
    return result
}
  • Compiler Error
  • 0
    1
    2
    3
    4
    5
    0
    1
    2
    3
    4
    5
  • 0
    2
    4
    6
    8
    10
    00
    11
    22
    33
    44
    55
  • None of the above

Quiz 9: Reading and Writing

Q1. If the following program is written in file main.go, and is executed via the command line as go run main.go Evan Michael Laura what will the output be?

package main
import (
    "fmt"
    "os"
    "strings"
)

func main() {
    who := "World"
    
    if len(os.Args) > 1 { // os.Args[0] == hello_who
        who = strings.Join(os.Args[1:], " ")
    }
    fmt.Println("Hello", who, "!")
}
  • Hello Evan Michael Laura !
  • Hello World !
  • Hello Evan Michael Laura World !

Q2. What is the following program doing?

package main
import (
    "fmt"
    "io"
    "bufio"
    "os"
)

func main() {
    inputFile, _ := os.Open("input.txt")
    outputFile, _ := os.OpenFile("output.txt", os.O_WRONLY|os.O_CREATE, 0666)
    defer inputFile.Close()
    defer outputFile.Close()
    inputReader := bufio.NewReader(inputFile)
    outputWriter := bufio.NewWriter(outputFile)
    for {
        inputString, _, readerError := inputReader.ReadLine()
        if readerError == io.EOF {
            fmt.Println("EOF")
            break
        }
        outputString := string([]byte(inputString)[2:5]) + "\r\n"
        _, err := outputWriter.WriteString(outputString)
        if (err != nil) {
            fmt.Println(err)
            return
        }
    }
    outputWriter.Flush()
}
  • Retaining the 2nd line to 5th line inclusively from input.txt file in output.txt.
  • Retaining the 2nd line to 4th line inclusively from input.txt file in output.txt.
  • Retaining the 2nd to the 5th character inclusively of every line from input.txt file in output.txt.
  • Retaining the 2nd to the 4th character inclusively of every line from input.txt file in output.txt.

Quiz 10: Error-Handling and Testing

Q1. What is the outcome of a program calling the recursive function f with value 5?

func f(n int) {
  defer func() { fmt.Println(n) }()
  if n == 0 {
    panic(0)
  }
  f(n-1)
}
  • 0
    1
    2
    3
    4
    5
  • 5
    4
    3
    2
    1
    0
  • Throws a panic
  • Both A and C

Q2. What is the output of the following program?

package main
import (
    "fmt"
)

func main() {
    fmt.Println(f(4,2))
    fmt.Println(f(7,0))
}

func f(x, y int) (z int) {
    defer func() {
        if err := recover(); err != nil {
            fmt.Println(err)
            z = 0
        }
    }()
    return x / y
}
  • 2
    runtime error: integer divide by zero
    0
  • 2
    0
  • 2
    runtime error: integer divide by zero
  • None of the above

Q3. What is the output of the following program?

package main
import "fmt"

func main() {
    f()
    fmt.Println("Returned normally from f.")
}

func f() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered in f", r)
        }
    }()
    fmt.Println("Calling g.")
    g(0)
    fmt.Println("Returned normally from g.")
}

func g(i int) {
    if i > 3 {
        fmt.Println("Panicking!")
        panic(fmt.Sprintf("%v", i))
    }
    defer fmt.Println("Defer in g", i)
    fmt.Println("Printing in g", i)
    g(i + 1)
}
  • Calling g.
    Panicking!
    Defer in g 0
    Printing in g 0
    Defer in g 1
    Printing in g 1
    Defer in g 2
    Printing in g 2
    Defer in g 3
    Printing in g 3
    Returned normally from g.
    Recovered in f 4
    Returned normally from f.
  • Calling g.
    Panicking!
    Defer in g 0
    Defer in g 1
    Defer in g 2
    Defer in g 3
    Printing in g 0
    Printing in g 1
    Printing in g 2
    Printing in g 3
    Returned normally from g.
    Recovered in f 4
    Returned normally from f.
  • Calling g.
    Panicking!
    Defer in g 0
    Defer in g 1
    Defer in g 2
    Defer in g 3
    Printing in g 3
    Printing in g 2
    Printing in g 1
    Printing in g 0
    Returned normally from g.
    Recovered in f 4
    Returned normally from f.
  • Calling g.
    Printing in g 0
    Printing in g 1
    Printing in g 2
    Printing in g 3
    Panicking!
    Defer in g 3
    Defer in g 2
    Defer in g 1
    Defer in g 0
    Recovered in f 4
    Returned normally from f.

Quiz 11: Goroutines and Channels

Q1. Deduce the output of the following program

package main
import (
    "fmt"
)

func tel(ch chan int) {
    for i := 0; i < 5; i++ {
        ch <- i
    }
}

func main() {
    ok := true
    ch := make(chan int)

    go tel(ch)
    for ok {
        i, ok := <-ch
        fmt.Printf("ok is %t and the counter is at %d\n", ok, i)
    }
}
  • ok is true and the counter is at 0
    ok is true and the counter is at 1
    ok is true and the counter is at 2
    ok is true and the counter is at 3
    ok is true and the counter is at 4
  • fatal error: all goroutines are asleep - deadlock!
  • Both of A and B
  • None of the above

Q2. Deduce the output of the following program:

package main

import (
    "fmt"
)

func tel(ch chan int) {
    for i:=0; i < 5; i++ {
        ch <- i
    }
    close(ch) // if this is ommitted: fatal error: all goroutines are asleep - deadlock!
}

func main() {
    i := 0
    ch := make(chan int)

    go tel(ch)

    for i = range ch {
            fmt.Printf("the counter is at %d\n", i)
    }
}
  • the counter is at 0
    the counter is at 1
    the counter is at 2
    the counter is at 3
    the counter is at 4
  • fatal error: all goroutines are asleep - deadlock!
  • Both A and B
  • None of the above

Q3. Deduce the output of the following program:

package main
import (
    "fmt"
    "os"
)

func tel(ch chan int, quit chan bool) {
    for i:=0; i < 5; i++ {
        ch <- i
    }
    quit <- true
}

func main() {
    ch := make(chan int)
    quit := make(chan bool)

    go tel(ch, quit)
    for {
        select {
        case i:= <-ch:
            fmt.Printf("The counter is at %d\n", i)
        case <-quit:
            os.Exit(0)
            // break : gives a  deadlock on select (break only exits from select, not from for!)
        }
    }
}
  • the counter is at 0
    the counter is at 1
    the counter is at 2
    the counter is at 3
    the counter is at 4
  • fatal error: all goroutines are asleep - deadlock!
  • Both A and B
  • None of the above

Q4. Deduce the output of the following program:

package main
import (
    "fmt"
)

const TERM = 5

func main() {
    i := 0
    c := make(chan int)

    go terms(TERM, c)
    for {
        if result, ok := <-c; ok {
            fmt.Printf("value(%d) is: %d\n", i, result)
            i++
        }
    }
}

func terms(TERM int, c chan int) {
    for i := 0; i <= TERM; i++ {
        c <- calculate(i)
    }
    close(c)
}

func calculate(n int) (res int) {
    if n <= 1 {
        res = 1
    } else {
        res = calculate(n-1) + calculate(n-2)
    }
    return
}
  • Throws a panic
  • Infinite loop
  • value(0) is: 1
    value(1) is: 1
    value(2) is: 2
    value(3) is: 3
    value(4) is: 5
    value(5) is: 8
  • Both B and C

Q5. Deduce the output of the following program:

package main
import (
    "fmt"
)

func main() {
    fmt.Println(Calculate(4))
}

func Calculate(n int) float64 {
    ch := make(chan float64)
    for k := 0; k <= n; k++ {
        go term(ch, float64(k))
    }
    f := 0.0
    for k := 0; k <= n; k++ {
        f += <-ch
    }
    return f
}

func term(ch chan float64, k float64) {
    ch <- 4 * k
}
  • 4
  • 40
  • 256
  • None of the above
Conclusion:

I hope this The Way to Go Educative Quiz Answers would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published. Required fields are marked *