Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
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.
Q1. Which of the following are features of Golang?
Q2. Which features are missing from Go?
Q3. Which of the following statements is False?
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)
}
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)
}
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)
}
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
}
Q2. What will the following function return for x=-10
?
func Abs(x int) int {
if x < 0 {
return -x
}
return x
}
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)
}
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)
}
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")
}
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)
}
i
Q7. What will this loop print out?
for i := 0; i < 5; i++ {
var v int
fmt.Printf("%d ", v)
v = 5
}
Q8. Which of the following is an infinite loop?
for i := 0; ; i++ {
fmt.Println("Value of i is now:", i)
}
for i := 0; i < 3; {
fmt.Println("Value of i:", i)
}
Q9. What will this loop print out?
s := ""
for ; s != "aaaaa"; {
fmt.Println("Value of s:", s)
s = s + "a"
}
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)
}
Q11. What is the output of the following code?
LOOP:
for i := 0; i < 10; i++ {
if i == 5 {
break LOOP
}
fmt.Println(i)
}
Q12. What is the output of the following code?
LOOP:
for i := 0; i < 10; i++ {
if i == 5 {
continue LOOP
}
fmt.Println(i)
}
Q13. What will the following loop print out?
LOOP:
for i := 0; i < 10; i++ {
if i == 5 {
goto LOOP
}
fmt.Println(i)
}
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.")
Q15. What will the following loop print out?
for i := 0; i<7 ; i++ {
if i%2 == 0 { continue }
fmt.Println("Odd:", i)
}
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
.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
}
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
}
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
}
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()
}
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)
}
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())
}
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))
}
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])
}
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])
}
}
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
}
}
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[:]
?
b[1:4]
is 4 and 5 respectively.b[:2]
is 3 and 6 respectively.b[2:]
is 2 and 4 respectively.b[:]
is 6 and 6 respectively.b[1:4]
is 3 and 2 respectively.b[:2]
is 2 and 4 respectively.b[2:]
is 4 and 2 respectively.b[:]
is 6 and 0 respectively.b[1:4]
is 3 and 5 respectively.b[:2]
is 2 and 6 respectively.b[2:]
is 4 and 2 respectively.b[:]
is 6 and 0 respectively.b[1:4]
is 3 and 5 respectively.b[:2]
is 2 and 6 respectively.b[2:]
is 4 and 4 respectively.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 ?
s
are 4 and 4.s
are 2 and 3.s
are 5 and 5.s
are 2 and 3.s
are 5 and 5.s
are 3 and 2.s
are 4 and 4.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?
s2
= {‘e’,‘m’}s2
= {‘e’,‘t’}s2
= {‘p’,‘o’}s2
= {‘p’,‘t’}s2
= {‘o’,‘e’,‘m’}s2
= {‘o’,‘t’,‘m’}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
}
Q8. If s
is a slice, what is the length of s[n:n]
and s[n:n+1]
?
s[n:n]
is 1.s[n:n+1]
is 2.s[n:n]
is 4.s[n:n+1]
is 5.s[n:n]
is 3.s[n:n+1]
is 4.s[n:n]
is 0.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.
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:]
}
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
}
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
}
task1
returns 2 and task2
returns 643.task2
returns 2 and task1
returns 643.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"])
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])
}
Q3. Which statement is true for the following code snippet?
capitals := map[string] int {"France":0, "Italy":1, "Japan":2 }
val, isPresent := capitals["France"]
val
is 0, because France
key doesn’t exist.val
is 0, because France
key is associated with 0 at time of declaration.isPresent
is false.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])
}
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 objectlist.List
lst.Iter
undefined (type *list.List
has no field or method Iter
)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()
}
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())
}
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)
}
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)
}
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)
}
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
}
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
}
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
}
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, "!")
}
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()
}
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)
}
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
}
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)
}
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)
}
}
all goroutines are asleep - deadlock!
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)
}
}
all goroutines are asleep - deadlock!
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!)
}
}
}
all goroutines are asleep - deadlock!
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
}
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
}
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 >>