0% found this document useful (0 votes)
2 views

COMP3007 Modern Programming Languages Final Worksheet

The document is an assessment for a Go programming course, consisting of multiple-choice questions covering various aspects of the language, including variable declaration, data types, control structures, and functions. Each question includes the correct answer and a brief explanation. The assessment is designed to evaluate the understanding of Go programming concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

COMP3007 Modern Programming Languages Final Worksheet

The document is an assessment for a Go programming course, consisting of multiple-choice questions covering various aspects of the language, including variable declaration, data types, control structures, and functions. Each question includes the correct answer and a brief explanation. The assessment is designed to evaluate the understanding of Go programming concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

COMP 3007: Modern Programming Languages

Go Programming Assessment
Fall 2024

Multiple Choice Questions (100 points)


Instructions: Choose the best answer for each question. Each question is worth 1 point.

1. What is the zero value for an integer type in Go?

a) null
b) undefined
c) 0
d) nil

Answer: c) 0
Explanation: In Go, each type has a zero value. For numeric types (including inte-
gers), the zero value is 0. This is automatically assigned when a variable is declared
but not explicitly initialized.

2. Which of the following is the correct way to declare and initialize a variable in Go?

a) var x := 5
b) x := 5
c) let x = 5
d) int x = 5

Answer: b) x := 5
Explanation: The := operator is the short declaration operator in Go. It declares
and initializes a variable in one step. The type is inferred from the value. This is
commonly used within functions.

3. What is the size of an int in Go?

a) Always 32 bits
b) Always 64 bits
c) Platform dependent (32 or 64 bits)

1
d) 16 bits

Answer: c) Platform dependent (32 or 64 bits)


Explanation: In Go, the size of int depends on the platform: it’s 32 bits on 32-bit
systems and 64 bits on 64-bit systems. For explicit sizing, you can use int32 or int64.

4. Which of the following is true about strings in Go?

a) They are mutable


b) They are immutable
c) They can be null
d) They don’t have a zero value

Answer: b) They are immutable


Explanation: Strings in Go are immutable sequences of bytes. Once created, you
cannot modify individual characters of a string. To modify a string, you need to create
a new string.

5. What is the zero value for a boolean type in Go?

a) nil
b) undefined
c) true
d) false

Answer: d) false
Explanation: In Go, the zero value for a boolean type is false. This is automatically
assigned when a boolean variable is declared but not explicitly initialized.

6. Which of the following correctly declares a constant in Go?

a) const x = 5
b) constant x = 5
c) let const x = 5
d) x := const 5

Answer: a) const x = 5
Explanation: In Go, constants are declared using the const keyword. They must be
initialized at declaration time and cannot be changed afterward.

7. What is the type of a numeric constant in Go without an explicit type declaration?

a) Always int
b) Always float64

2
c) Untyped
d) Platform dependent

Answer: c) Untyped
Explanation: Numeric constants in Go are untyped until they are used in a context
that requires a type. This allows them to be used flexibly with different numeric types
without explicit conversion.

8. Which of the following is the correct way to perform integer division in Go?

a) x / y
b) x div y
c) x // y
d) integer(x/y)

Answer: a) x / y
Explanation: In Go, the / operator performs integer division when both operands are
integers. If you want floating-point division, at least one operand must be a floating-
point number.

9. What happens when you try to assign a value to an undeclared variable in Go?

a) It works fine
b) Runtime error
c) Compilation error
d) The variable gets automatically declared

Answer: c) Compilation error


Explanation: Go requires all variables to be declared before use. Attempting to
assign a value to an undeclared variable results in a compilation error. This is part of
Go’s emphasis on explicit declarations.

10. What is the purpose of the blank identifier (_) in Go?

a) To create empty variables


b) To ignore unwanted values
c) To declare private variables
d) To initialize variables to zero

Answer: b) To ignore unwanted values


Explanation: The blank identifier (_) in Go is used to ignore values that you don’t
want to use. It’s commonly used in multiple assignment contexts where you only need
some of the returned values.

3
11. What is the difference between arrays and slices in Go?

a) Arrays are mutable, slices are immutable


b) Arrays have fixed length, slices are dynamic
c) Slices can only be created from arrays
d) Arrays are faster than slices

Answer: b) Arrays have fixed length, slices are dynamic


Explanation: In Go, arrays have a fixed length that is part of their type (e.g., [5]int),
while slices are dynamic and can grow or shrink. Slices are more commonly used in
Go programs because of their flexibility.

12. How do you create a slice in Go?

a) var s []int = new([]int)


b) s := make([]int, 5)
c) s := []int{size: 5}
d) s := new([]int, 5)

Answer: b) s := make([]int, 5)
Explanation: The make function is used to create slices in Go. It allows you to
specify the length and optionally the capacity. You can also create slices using literal
syntax ([]int) or by slicing existing arrays/slices.

13. What is the capacity of a slice in Go?

a) The current number of elements


b) The maximum allowed elements
c) The size of the underlying array
d) The minimum guaranteed size

Answer: c) The size of the underlying array


Explanation: A slice’s capacity is the size of the underlying array, starting from the
slice’s first element. It represents the maximum length the slice can grow to without
requiring reallocation.

14. Which operation will panic when performed on a nil slice?

a) len(slice)
b) cap(slice)
c) append(slice, element)
d) slice[0]

4
Answer: d) slice[0]
Explanation: Attempting to access elements of a nil slice using index notation will
cause a panic. However, len(), cap(), and append() are safe to use on nil slices - len
and cap return 0, and append creates a new slice.

15. What happens when you append to a slice that has reached its capacity?

a) The append fails


b) A new array is allocated with greater capacity
c) The program panics
d) The element is ignored

Answer: b) A new array is allocated with greater capacity


Explanation: When a slice’s length would exceed its capacity after append, Go al-
locates a new underlying array with greater capacity (typically double the current
capacity), copies the existing elements, and returns a slice that references the new
array.

16. How do you declare a map in Go?

a) map[string]int{}
b) make(map[string]int)
c) Both a and b are correct
d) new(map[string]int)

Answer: c) Both a and b are correct


Explanation: Maps in Go can be created either using the literal syntax map[Key-
Type]ValueType or using make(map[KeyType]ValueType). The make function is pre-
ferred when you don’t need to initialize the map with any key-value pairs.

17. What happens when you try to add a key-value pair to a nil map?

a) The pair is added successfully


b) Nothing happens
c) The program panics
d) A compilation error occurs

Answer: c) The program panics


Explanation: Attempting to add a key-value pair to a nil map causes a runtime
panic. Maps must be initialized using make() or map literal syntax before they can be
used for storing data.

18. What is returned when accessing a non-existent key in a map?

5
a) nil
b) panic
c) The zero value of the value type
d) An error

Answer: c) The zero value of the value type


Explanation: When accessing a non-existent key in a map, Go returns the zero value
for the map’s value type (0 for int, ”” for string, false for bool, etc.). You can use the
two-value form of map access to check if a key exists.

19. What is the correct way to check if a key exists in a map?

a) if m[key] != nil { ... }


b) if m.contains(key) { ... }
c) value, exists := m[key]; if exists { ... }
d) if m.hasKey(key) { ... }

Answer: c) value, exists := m[key]; if exists { ... }


Explanation: The two-value assignment form of map access returns both the value
and a boolean indicating whether the key exists. This is the idiomatic way to check
for key existence in Go.

20. Which of the following is true about map iteration order in Go?

a) It’s always in insertion order


b) It’s always in key order
c) It’s random and unspecified
d) It’s in reverse insertion order

Answer: c) It’s random and unspecified


Explanation: The iteration order of maps in Go is deliberately randomized and
unspecified. You should not rely on any particular order when iterating over map
keys. If you need a specific order, you should sort the keys explicitly.

21. What is variable shadowing in Go?

a) When a variable is not used


b) When a variable in an inner scope hides a variable in an outer scope
c) When two variables have the same type
d) When a variable is declared but not initialized

6
Answer: b) When a variable in an inner scope hides a variable in an outer scope
Explanation: Variable shadowing occurs when you declare a new variable with the
same name as a variable in an outer scope. The inner variable ”shadows” the outer
one, making it inaccessible within that block.

22. Which of the following is a valid if statement initialization in Go?

a) if x := getValue(); x > 0 { ... }


b) if (x = getValue()) > 0 { ... }
c) if let x = getValue(); x > 0 { ... }
d) if x > 0 where x = getValue() { ... }

Answer: a) if x := getValue(); x > 0 { ... }


Explanation: Go allows an initialization statement before the condition in an if
statement, separated by a semicolon. The variable declared in this initialization is
only available within the if block and any associated else blocks.

23. What is the scope of a variable declared in a for loop initialization?

a) Global scope
b) Package scope
c) The entire function
d) Only within the for loop

Answer: d) Only within the for loop


Explanation: Variables declared in the initialization part of a for loop (e.g., for i
:= 0; i < 10; i++) are only accessible within the loop block. This creates a new
scope specific to the loop.

24. Which of the following is the correct way to write an infinite loop in Go?

a) for (;;) { ... }


b) while (true) { ... }
c) for { ... }
d) loop { ... }

Answer: c) for { ... }


Explanation: In Go, an infinite loop is written simply as for without any conditions.
This is the idiomatic way to write infinite loops, and it’s equivalent to for true but
more concise.

25. How do you write a traditional while loop in Go?

a) while condition { ... }

7
b) for condition { ... }
c) do { ... } while condition
d) loop while condition { ... }
Answer: b) for condition { ... }
Explanation: Go doesn’t have a while keyword. Instead, a while loop is written using
for with a condition. This is part of Go’s philosophy of having fewer keywords and
simpler syntax.
26. What is special about the switch statement in Go compared to other languages?
a) It requires a default case
b) Break statements are implicit
c) Cases must be constants
d) It can only switch on integers
Answer: b) Break statements are implicit
Explanation: In Go, switch statements automatically break after each case. You
don’t need to write explicit break statements. If you want execution to fall through to
the next case, you can use the fallthrough keyword.
27. Which statement is used to jump to the next iteration of a loop in Go?
a) next
b) continue
c) skip
d) pass
Answer: b) continue
Explanation: The continue statement is used to skip the rest of the current itera-
tion and move to the next iteration of a loop. This is consistent with other C-style
languages.
28. What is the purpose of the fallthrough statement in Go?
a) To exit a switch statement
b) To force execution of the next case in a switch
c) To handle errors
d) To skip the current iteration of a loop
Answer: b) To force execution of the next case in a switch
Explanation: fallthrough forces execution to continue into the next case in a switch
statement, even if its condition doesn’t match. This is rarely needed in Go because
cases don’t automatically fall through like in C.

8
29. Which of the following is true about Go’s type switch?

a) It can only be used with interfaces


b) It requires type assertions
c) It can switch on any expression
d) It doesn’t support default cases

Answer: a) It can only be used with interfaces


Explanation: A type switch in Go is used to check the concrete type of an interface
value. It uses the special syntax switch v := x.(type) and can only be used with
interface values.

30. What happens if no case matches in a switch statement without a default case?

a) The program panics


b) The switch statement is skipped
c) A compilation error occurs
d) The first case is executed

Answer: b) The switch statement is skipped


Explanation: If no case matches and there is no default case in a switch statement,
the entire switch block is skipped and execution continues after the switch. This is
safe and doesn’t cause any errors.

31. Which of the following is a correct way to declare a function with multiple return
values in Go?

a) func divide(x, y int) (int, error)


b) func divide(x, y int) -> (int, error)
c) func divide(x, y int) return int, error
d) func divide(x, y int) [int, error]

Answer: a) func divide(x, y int) (int, error)


Explanation: Go functions can return multiple values by listing them in parentheses.
This is commonly used for returning both a result and an error value.

32. What is a variadic function in Go?

a) A function that returns multiple values


b) A function that takes a variable number of arguments
c) A function that can change its return type
d) A function without parameters

9
Answer: b) A function that takes a variable number of arguments
Explanation: A variadic function can accept a variable number of arguments of the
same type. It’s declared using ... before the type of the last parameter, like func
sum(nums ...int).

33. What is the purpose of named return values in Go?

a) They make the code more readable


b) They allow empty returns
c) Both a and b
d) They improve performance

Answer: c) Both a and b


Explanation: Named return values serve two purposes: they document the meaning
of return values, making code more readable, and they allow the use of ”naked” return
statements (return without arguments) as the values are pre-declared.

34. How do you declare a function type in Go?

a) type Handler = func(string) error


b) typedef func(string) error Handler
c) interface Handler { func(string) error }
d) type Handler interface { func(string) error }

Answer: a) type Handler = func(string) error


Explanation: Function types in Go are declared using the type keyword followed by
the function signature. This allows you to create variables that can hold functions
with specific signatures.

35. What happens when you call a function with fewer arguments than parameters in Go?

a) The missing arguments are set to zero values


b) The program panics
c) A compilation error occurs
d) The function uses default values

Answer: c) A compilation error occurs


Explanation: Go requires that all function parameters be provided unless the pa-
rameter is variadic. Attempting to call a function with too few arguments results in a
compilation error.

36. What is the difference between a method and a function in Go?

a) Methods can only be called on structs

10
b) Methods have a receiver parameter
c) Methods can’t return multiple values
d) Methods must have a return value
Answer: b) Methods have a receiver parameter
Explanation: A method is a function with a receiver parameter that specifies the
type it operates on. The receiver appears between the func keyword and the method
name. Regular functions don’t have receivers.
37. How do you make a function available outside its package in Go?
a) Use the public keyword
b) Start the function name with a capital letter
c) Add an export statement
d) Mark it with @public annotation
Answer: b) Start the function name with a capital letter
Explanation: In Go, identifier visibility is determined by case. Functions (and other
identifiers) that start with a capital letter are exported and accessible from other
packages. Those starting with lowercase are package-private.
38. What is a closure in Go?
a) A function that returns another function
b) A function that doesn’t return a value
c) A function that captures variables from its surrounding scope
d) A function that can’t access global variables
Answer: c) A function that captures variables from its surrounding scope
Explanation: A closure is a function value that references variables from outside its
body. The function may access and modify the variables referenced by the closure,
even after the enclosing function has finished executing.
39. What is the purpose of the defer statement in Go?
a) To delay function execution until the surrounding function returns
b) To handle errors in functions
c) To create asynchronous functions
d) To skip function execution
Answer: a) To delay function execution until the surrounding function returns
Explanation: The defer statement schedules a function call to be run just before the
surrounding function returns. This is often used for cleanup operations like closing
files or network connections.

11
40. In what order are deferred function calls executed?

a) First deferred, first executed


b) Last deferred, first executed
c) Random order
d) Alphabetical order by function name

Answer: b) Last deferred, first executed


Explanation: Deferred function calls are pushed onto a stack and executed in last-
in-first-out (LIFO) order when the surrounding function returns. This means the last
deferred call is executed first.

41. How do you declare a pointer variable in Go?

a) ptr *int = &x


b) ptr = pointer(int)
c) ptr -> int
d) ptr ref int

Answer: a) ptr *int = &x


Explanation: In Go, pointers are declared using the * symbol before the type. The
& operator is used to get the address of a variable. This creates a pointer that holds
the memory address of the variable.

42. What is the zero value of a pointer in Go?

a) 0
b) undefined
c) null
d) nil

Answer: d) nil
Explanation: The zero value of a pointer in Go is nil. This represents a pointer that
doesn’t point to any memory address. Attempting to dereference a nil pointer will
cause a panic.

43. What happens when you dereference a nil pointer in Go?

a) Returns zero value


b) Compilation error
c) Runtime panic
d) Returns nil

12
Answer: c) Runtime panic
Explanation: Dereferencing a nil pointer in Go causes a runtime panic. This is a
safety feature that prevents accessing invalid memory addresses. Always check if a
pointer is nil before dereferencing it.

44. What is the correct way to create a pointer to a struct in Go?

a) new(MyStruct)
b) &MyStruct{}
c) Both a and b are correct
d) make(MyStruct)

Answer: c) Both a and b are correct


Explanation: In Go, you can create a pointer to a struct either using the new()
function or using the & operator with a struct literal. Both approaches are idiomatic
and create a pointer to a zero-valued struct.

45. What is pointer receiver in Go methods?

a) A method that returns a pointer


b) A method that takes a pointer parameter
c) A method with a pointer as its receiver
d) A method that creates pointers

Answer: c) A method with a pointer as its receiver


Explanation: A pointer receiver is declared using *Type in the method’s receiver
declaration. It allows the method to modify the receiver and avoids copying the value
on method calls. For example: func (p *Person) SetName(name string).

46. When should you use a pointer receiver instead of a value receiver?

a) When the receiver is a large struct


b) When the method needs to modify the receiver
c) When working with maps or slices
d) Both a and b

Answer: d) Both a and b


Explanation: Pointer receivers should be used when the method needs to modify the
receiver’s state or when the receiver is a large struct to avoid copying. Value receivers
are used when the method doesn’t modify the receiver and the receiver is small.

47. What does the new() function return in Go?

a) A zero-valued variable

13
b) A pointer to a zero-valued variable
c) An uninitialized variable
d) A nil pointer
Answer: b) A pointer to a zero-valued variable
Explanation: The new() function allocates memory for a type, sets it to its zero value,
and returns a pointer to it. For example, new(int) returns a pointer to a zero-valued
int.
48. Which of the following correctly accesses a struct field through a pointer?
a) ptr->field
b) (*ptr).field
c) ptr.field
d) Both b and c
Answer: d) Both b and c
Explanation: In Go, you can access struct fields through a pointer either using
explicit dereferencing (*ptr).field or using the shorthand ptr.field. The -> operator
from C/C++ doesn’t exist in Go.
49. What happens when you pass a pointer to a function in Go?
a) The pointer is copied
b) The pointed-to value is copied
c) Both pointer and value are copied
d) A new pointer is created
Answer: a) The pointer is copied
Explanation: When passing a pointer to a function, Go makes a copy of the pointer
value (the memory address), not the value it points to. This means multiple pointers
can point to the same memory location.
50. Can you perform pointer arithmetic in Go?
a) Yes, like in C
b) No, it’s not allowed
c) Only with unsafe package
d) Only with integers
Answer: b) No, it’s not allowed
Explanation: Go deliberately does not support pointer arithmetic to improve safety
and simplicity. While it’s technically possible using the unsafe package, it’s discouraged
and breaks Go’s memory safety guarantees.

14
51. What is the correct way to define a new type in Go?

a) typedef string Username


b) type Username = string
c) type Username string
d) new type Username string

Answer: c) type Username string


Explanation: In Go, new types are defined using the type keyword followed by the
new type name and the underlying type. This creates a distinct type that has the
same underlying representation as the base type.

52. What is type embedding in Go?

a) A form of inheritance
b) Including one type inside another without a field name
c) Creating type aliases
d) Converting between types

Answer: b) Including one type inside another without a field name


Explanation: Type embedding in Go allows you to include one type within another
without giving it a field name. This provides a way to reuse code and compose types,
but it’s not inheritance in the traditional object-oriented sense.

53. How does Go implement inheritance?

a) Using the extends keyword


b) Using interfaces
c) Using type embedding
d) Go doesn’t have inheritance

Answer: d) Go doesn’t have inheritance


Explanation: Go deliberately doesn’t support traditional inheritance. Instead, it uses
composition through type embedding and interfaces for code reuse and polymorphism.
This is part of Go’s philosophy of keeping the language simple and explicit.

54. What is the difference between a type definition and a type alias in Go?

a) They are the same thing


b) Type definition creates a new type, alias creates a synonym
c) Aliases can’t have methods
d) Definitions can’t implement interfaces

15
Answer: b) Type definition creates a new type, alias creates a synonym
Explanation: A type definition (type MyInt int) creates a completely new type,
while a type alias (type MyInt = int) creates another name for an existing type.
The new type can have its own methods, while the alias is completely interchangeable
with the original type.

55. Which statement correctly implements an interface in Go?

a) type MyType implements MyInterface


b) type MyType : MyInterface
c) No explicit declaration needed, just implement the methods
d) implement MyInterface for MyType

Answer: c) No explicit declaration needed, just implement the methods


Explanation: Go uses implicit interface implementation. If a type implements all the
methods specified by an interface, it automatically implements that interface. There’s
no need for explicit declaration like ”implements” keywords found in other languages.

56. What is an empty interface in Go?

a) An interface with no implementation


b) An interface that can’t be implemented
c) An interface with no methods
d) A nil interface

Answer: c) An interface with no methods


Explanation: An empty interface (interface{}) has no methods, so every type imple-
ments it by default. It can hold values of any type, making it useful for functions that
need to handle values of unknown types.

57. What happens if a type doesn’t implement all methods of an interface?

a) Runtime error
b) Compilation error
c) Default implementation is used
d) Missing methods return nil

Answer: b) Compilation error


Explanation: If a type is used in a context where it needs to satisfy an interface but
doesn’t implement all the interface’s methods, the Go compiler will produce an error.
This ensures type safety at compile time.

58. What is type assertion in Go?

16
a) Converting between types
b) Checking if an interface holds a specific type
c) Declaring type constraints
d) Creating type aliases

Answer: b) Checking if an interface holds a specific type


Explanation: Type assertion provides a way to access the underlying concrete type of
an interface value. The syntax value, ok := interfaceValue.(Type) either returns
the underlying value and true if the type matches, or the zero value and false if it
doesn’t.

59. What is type switch in Go used for?

a) Converting between multiple types


b) Switching between different implementations
c) Testing an interface value against multiple types
d) Creating conditional type definitions

Answer: c) Testing an interface value against multiple types


Explanation: A type switch is a construct that permits several type assertions in
series. It’s similar to a regular switch statement but the cases specify types instead of
values, allowing you to handle different types of values in different ways.

60. What is the purpose of the Stringer interface in Go?

a) To convert strings to other types


b) To define custom string representation of types
c) To concatenate strings
d) To handle string encoding

Answer: b) To define custom string representation of types


Explanation: The Stringer interface from the fmt package defines a String() method
that returns a string representation of a value. Types that implement this interface
can control how they are printed when using functions like fmt.Println.

61. What is the error interface in Go?

a) type error interface { Error() string }


b) type error interface { String() string }
c) type error interface { Message() string }
d) type error interface { GetError() string }

17
Answer: a) type error interface { Error() string }
Explanation: The error interface in Go is a built-in interface that requires a single
method Error() returning a string. Any type that implements this method satisfies
the error interface and can be used as an error value.

62. What is the idiomatic way to handle errors in Go?

a) Using try-catch blocks


b) Using if err != nil checks
c) Using throw statements
d) Using error codes

Answer: b) Using if err != nil checks


Explanation: Go handles errors explicitly using return values. The idiomatic pattern
is to check if an error is not nil immediately after a function call that can return an
error. This makes error handling explicit and visible.

63. How do you create a custom error type in Go?

a) type MyError struct { msg string }


b) class MyError extends error
c) type MyError error
d) new Error(msg string)

Answer: a) type MyError struct { msg string }


Explanation: To create a custom error type in Go, you typically define a struct and
implement the error interface by adding an Error() string method. This allows you to
create errors with additional context or behavior.

64. What is error wrapping in Go?

a) Converting errors to strings


b) Adding context to existing errors
c) Hiding error details
d) Ignoring errors

Answer: b) Adding context to existing errors


Explanation: Error wrapping in Go (introduced in Go 1.13) allows you to add ad-
ditional context to an error while preserving the underlying error. This is done using
fmt.Errorf with the

65. How do you check if an error is a specific type?

a) if err.type == MyError

18
b) errors.Is(err, MyError)
c) if err instanceof MyError
d) switch err.(type)
Answer: b) errors.Is(err, MyError)
Explanation: The errors.Is function is used to check if an error (or any error it wraps)
matches a specific error value. For custom error types, you can also use type assertions
or type switches.
66. What is the purpose of errors.As in Go?
a) To convert errors to strings
b) To find the first error in a chain that matches a type
c) To combine multiple errors
d) To ignore errors
Answer: b) To find the first error in a chain that matches a type
Explanation: errors.As searches through an error chain for the first error that can
be converted to a specified type. It’s useful when you need to access the methods or
fields of a specific error type in the chain.
67. What’s the difference between panic and error in Go?
a) Errors are recoverable, panics are not
b) Panics are recoverable, errors are not
c) They are the same thing
d) Panics are for logging only
Answer: a) Errors are recoverable, panics are not
Explanation: Errors in Go represent expected problems and are handled through
normal control flow. Panics represent unrecoverable situations and crash the program
(unless recovered). Errors should be used for most error handling.
68. How do you recover from a panic in Go?
a) Using try-catch
b) Using defer and recover()
c) Using error handling
d) Panics cannot be recovered
Answer: b) Using defer and recover()
Explanation: To recover from a panic in Go, you use the defer statement with a
function that calls recover(). If recover() is called during a panic, it captures the panic
value and returns normal execution.

19
69. What happens when a deferred function panics?

a) The program continues normally


b) Only that deferred function is skipped
c) All remaining deferred functions run
d) The program exits immediately

Answer: c) All remaining deferred functions run


Explanation: When a deferred function panics, the remaining deferred functions in
the stack still run. This ensures that cleanup code gets executed even in the presence
of panics, making defer useful for cleanup and recovery.

70. What is sentinel error in Go?

a) A predefined error value


b) A type of panic
c) An error that can’t be handled
d) A logging mechanism

Answer: a) A predefined error value


Explanation: A sentinel error is a predefined error value that is exported from a
package to be used for comparison. For example, io.EOF is a sentinel error. However,
creating custom sentinel errors is generally discouraged in favor of error types.

71. What is a goroutine in Go?

a) A type of error handling


b) A lightweight thread managed by the Go runtime
c) A type of channel
d) A synchronization primitive

Answer: b) A lightweight thread managed by the Go runtime


Explanation: A goroutine is a lightweight thread of execution managed by the Go
runtime. Goroutines are much cheaper than operating system threads and are the
basic building block of Go concurrency.

72. How do you start a new goroutine?

a) go.start(function)
b) thread.new(function)
c) go function()
d) async function()

20
Answer: c) go function()
Explanation: To start a new goroutine, you prefix a function or method call with
the go keyword. This starts the function running concurrently with the rest of the
program.

73. What is the purpose of channels in Go?

a) To create goroutines
b) To provide synchronized communication between goroutines
c) To handle errors in concurrent programs
d) To terminate goroutines

Answer: b) To provide synchronized communication between goroutines


Explanation: Channels are the primary mechanism for communication between gor-
outines in Go. They provide a way to send and receive values between goroutines with
synchronization built in.

74. What is a buffered channel in Go?

a) A channel that can store multiple values


b) A channel that only works with strings
c) A channel that automatically closes
d) A channel that can’t be closed

Answer: a) A channel that can store multiple values


Explanation: A buffered channel has a capacity for storing multiple values. Sends
to a buffered channel block only when the buffer is full, and receives block only when
the buffer is empty.

75. What happens when you send to a closed channel?

a) The value is discarded


b) A panic occurs
c) The channel reopens
d) The program deadlocks

Answer: b) A panic occurs


Explanation: Sending to a closed channel causes a panic. This is why it’s important
to coordinate channel closure carefully. However, receiving from a closed channel is
safe and returns the zero value for the channel’s type.

76. What is the select statement used for in Go?

a) To choose between multiple channel operations

21
b) To select goroutines to run
c) To select error handling strategies
d) To choose between function calls
Answer: a) To choose between multiple channel operations
Explanation: The select statement lets you wait on multiple channel operations
simultaneously. It will execute the first operation that becomes available, or a default
case if specified.
77. What is the purpose of sync.WaitGroup?
a) To synchronize access to shared memory
b) To wait for a collection of goroutines to finish
c) To create a group of channels
d) To handle group errors
Answer: b) To wait for a collection of goroutines to finish
Explanation: sync.WaitGroup is used to wait for a collection of goroutines to finish
executing. It provides Add(), Done(), and Wait() methods to coordinate the comple-
tion of multiple goroutines.
78. What is the purpose of sync.Mutex?
a) To lock a goroutine
b) To protect shared resources from concurrent access
c) To create mutual channels
d) To synchronize channel operations
Answer: b) To protect shared resources from concurrent access
Explanation: sync.Mutex provides mutual exclusion locks (mutexes) that prevent
multiple goroutines from accessing shared resources simultaneously, thereby preventing
race conditions.
79. What is a race condition in Go?
a) When goroutines compete to finish first
b) When multiple goroutines access shared data without synchronization
c) When channels are full
d) When select statements have no default case
Answer: b) When multiple goroutines access shared data without synchronization
Explanation: A race condition occurs when multiple goroutines access shared data
concurrently and at least one goroutine modifies the data. This can lead to unpre-
dictable behavior if proper synchronization isn’t used.

22
80. How can you detect race conditions in Go?

a) Using the -race flag with go build/run/test


b) Using fmt.Println
c) Race conditions can’t be detected
d) Using error handling

Answer: a) Using the -race flag with go build/run/test


Explanation: Go provides a built-in race detector that can be enabled by adding the
-race flag to go build, go run, or go test commands. This helps identify potential race
conditions in your code.

81. What is the naming convention for test files in Go?

a) test_file.go
b) file_test.go
c) file.test.go
d) _test.go

Answer: b) file_test.go
Explanation: Go test files must end with _test.go to be recognized by the Go test
tool. For example, if you have a file named math.go, its test file should be named
math_test.go.

82. What is the correct signature for a test function in Go?

a) func test(t *testing.T)


b) func Test(t *testing.T)
c) func TestFunction(t *testing.T)
d) func testCase(t *testing.T)

Answer: c) func TestFunction(t *testing.T)


Explanation: Test functions must start with ”Test” followed by a word starting with
an uppercase letter, and take a single parameter of type *testing.T. The function name
indicates what’s being tested.

83. How do you run tests in Go?

a) go run test
b) go test
c) go run tests
d) go check

23
Answer: b) go test
Explanation: The go test command runs all tests in the current package. You can
also specify a package path or use ./... to run tests in all subpackages.

84. What is the purpose of t.Error() in Go tests?

a) To log an error and continue testing


b) To immediately stop the test
c) To skip the test
d) To mark the test as inconclusive

Answer: a) To log an error and continue testing


Explanation: t.Error() reports a test failure but allows the test to continue running.
This is useful when you want to see multiple failures in a single test. In contrast,
t.Fatal() stops the test immediately.

85. How do you write a benchmark test in Go?

a) func TestBench(t *testing.T)


b) func Benchmark(t *testing.T)
c) func BenchmarkFunction(b *testing.B)
d) func Bench(b *testing.B)

Answer: c) func BenchmarkFunction(b *testing.B)


Explanation: Benchmark functions must start with ”Benchmark” and take a *test-
ing.B parameter. The testing.B type provides the b.N field which determines how
many times to run the benchmarked code.

86. What is the purpose of test tables in Go?

a) To organize test data


b) To run multiple test cases with different inputs
c) To benchmark different inputs
d) To create test documentation

Answer: b) To run multiple test cases with different inputs


Explanation: Table-driven tests in Go allow you to define multiple test cases in a
slice and run them all using a single test function. This reduces code duplication and
makes it easy to add new test cases.

87. How do you run a specific test in Go?

a) go test -run TestName


b) go test TestName

24
c) go test --test TestName
d) go run test TestName

Answer: a) go test -run TestName


Explanation: The -run flag allows you to specify a regular expression pattern that
matches the test functions you want to run. Only tests whose names match the pattern
will be executed.

88. What is the purpose of t.Parallel() in Go tests?

a) To run tests sequentially


b) To mark a test as capable of running in parallel
c) To create parallel benchmarks
d) To test parallel functions

Answer: b) To mark a test as capable of running in parallel


Explanation: Calling t.Parallel() marks a test as capable of running in parallel with
other parallel tests. This can speed up the test suite execution, but tests must be
carefully written to avoid race conditions.

89. How do you get test coverage information in Go?

a) go test -coverage
b) go test -cover
c) go coverage
d) go test --cov

Answer: b) go test -cover


Explanation: The -cover flag enables coverage analysis. You can also use -coverprofile
to save the coverage data to a file and then use go tool cover to generate HTML reports.

90. What is a test helper function in Go?

a) Any function used in tests


b) A function that starts with ”help”
c) A function that calls t.Helper()
d) A benchmark function

Answer: c) A function that calls t.Helper()


Explanation: A test helper function is a function that calls t.Helper(). This marks
the function as a helper, so when tests fail, the error is reported at the line where the
helper was called rather than inside the helper function.

91. What command initializes a new Go module?

25
a) go new mod
b) go mod init
c) go init module
d) go create mod

Answer: b) go mod init


Explanation: The go mod init command initializes a new module, creating a go.mod
file that specifies the module path and Go version requirements. This is typically the
first step in creating a new Go project.

92. What file contains Go module dependencies?

a) package.json
b) go.mod
c) dependencies.go
d) requirements.txt

Answer: b) go.mod
Explanation: The go.mod file contains the module’s dependencies, version require-
ments, and other module-specific information. It’s automatically managed by Go tools
and should be committed to version control.

93. What command downloads and installs packages named by the import paths?

a) go install
b) go get
c) go download
d) go fetch

Answer: b) go get
Explanation: The go get command downloads and installs packages and their de-
pendencies. In module-aware mode, it also updates go.mod and go.sum files to reflect
the downloaded dependencies.

94. What is the purpose of go fmt?

a) To compile Go code
b) To format Go code according to standard style
c) To check for syntax errors
d) To run tests

26
Answer: b) To format Go code according to standard style
Explanation: go fmt automatically formats Go source code according to the stan-
dard Go formatting style. This ensures consistent code formatting across the Go
ecosystem and eliminates style debates.

95. What command shows documentation for a package or symbol?

a) go help
b) go doc
c) go info
d) go man

Answer: b) go doc
Explanation: The go doc command prints documentation for a package, const, func,
type, var, or method. It can be used from the command line to quickly look up Go
documentation.

96. What is the purpose of go vet?

a) To format code
b) To find subtle bugs
c) To run tests
d) To compile code

Answer: b) To find subtle bugs


Explanation: go vet examines Go source code and reports suspicious constructs that
might be bugs. It can catch errors that a compiler might miss, such as printf format
string mismatches or incorrect struct tags.

97. How do you cross-compile Go code for a different operating system?

a) Use a different compiler


b) Set GOOS and GOARCH environment variables
c) Install OS-specific tools
d) Use conditional compilation

Answer: b) Set GOOS and GOARCH environment variables


Explanation: Go supports cross-compilation by setting the GOOS (target operating
system) and GOARCH (target architecture) environment variables before running go
build. For example, GOOS=linux GOARCH=amd64 go build.

98. What is the purpose of go generate?

a) To create new Go files

27
b) To run commands described by //go:generate comments
c) To generate documentation
d) To create test files

Answer: b) To run commands described by //go:generate comments


Explanation: go generate scans Go files for //go:generate comments and runs the
commands they specify. This is commonly used for code generation tasks like gener-
ating string methods for enums or embedding resources.

99. What command compiles and installs the packages in the main module?

a) go build
b) go compile
c) go make
d) go install

Answer: a) go build
Explanation: go build compiles the packages in the main module along with their
dependencies, but it doesn’t install the results. The compiled binary is placed in the
current directory.

100. What is the purpose of go work?

a) To manage workspace settings


b) To create new workspaces
c) To define multi-module workspaces
d) To run workspace tasks

Answer: c) To define multi-module workspaces


Explanation: The go work command, introduced in Go 1.18, manages go.work files
that define multi-module workspaces. This is useful when developing multiple related
modules simultaneously.

28

You might also like