COMP3007 Modern Programming Languages Final Worksheet
COMP3007 Modern Programming Languages Final Worksheet
Go Programming Assessment
Fall 2024
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.
a) Always 32 bits
b) Always 64 bits
c) Platform dependent (32 or 64 bits)
1
d) 16 bits
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.
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.
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
3
11. What is the difference between arrays and slices in Go?
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.
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) map[string]int{}
b) make(map[string]int)
c) Both a and b are correct
d) new(map[string]int)
17. What happens when you try to add a key-value pair to a nil map?
5
a) nil
b) panic
c) The zero value of the value type
d) An error
20. Which of the following is true about map iteration order in Go?
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.
a) Global scope
b) Package scope
c) The entire function
d) Only within the for loop
24. Which of the following is the correct way to write an infinite loop in Go?
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?
30. What happens if no case matches in a switch statement without a default case?
31. Which of the following is a correct way to declare a function with multiple return
values in Go?
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).
35. What happens when you call a function with fewer arguments than parameters in Go?
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) 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.
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.
a) new(MyStruct)
b) &MyStruct{}
c) Both a and b are correct
d) make(MyStruct)
46. When should you use a pointer receiver instead of a value receiver?
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) A form of inheritance
b) Including one type inside another without a field name
c) Creating type aliases
d) Converting between types
54. What is the difference between a type definition and a type alias in Go?
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.
a) Runtime error
b) Compilation error
c) Default implementation is used
d) Missing methods return nil
16
a) Converting between types
b) Checking if an interface holds a specific type
c) Declaring type constraints
d) Creating type aliases
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.
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) 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.
a) To create goroutines
b) To provide synchronized communication between goroutines
c) To handle errors in concurrent programs
d) To terminate goroutines
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) 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.
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.
24
c) go test --test TestName
d) go run test TestName
a) go test -coverage
b) go test -cover
c) go coverage
d) go test --cov
25
a) go new mod
b) go mod init
c) go init module
d) go create mod
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.
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.
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.
a) To format code
b) To find subtle bugs
c) To run tests
d) To compile code
27
b) To run commands described by //go:generate comments
c) To generate documentation
d) To create test files
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.
28