Question | Click to View Answer |
What does the following code print? package main
import "fmt"
func funify(word string) string {
return word + " is really fun!"
}
func main() {
fmt.Println(funify("cheese"))
}
|
The
|
What does the following code print? func add(a int, b int) int {
return a + b
}
func main() {
fmt.Println(add(3, 5))
}
|
The |
What does the following code print? func average(nums []float64) float64 {
total := 0.0
for _, v := range nums {
total += v
}
return total / float64(len(nums))
}
func main() {
scores := []float64{10, 11, 12, 13}
fmt.Println(average(scores))
}
|
The The |
What does the following code print? func product(a int, b int) (res int) {
res = a * b
return
}
func main() {
fmt.Println(product(5, 3))
}
|
The A return statement without arguments returns the named return values. This is known as a "naked" return. Naked returns should only be used in short functions. |
What does the following code print? func weird() (string, bool) {
return "casper", true
}
func main() {
if str, ok := weird(); ok {
fmt.Println(str, "is a ghost")
}
}
|
The
Go functions often return multiple values. |
What does the following code print? func addAll(nums ...int) int {
total := 0
for _, v := range nums {
total += v
}
return total
}
func main() {
fmt.Println(addAll(1, 2, 3, 4))
}
|
Both |
What does the following code print? func addAll(nums ...int) int {
total := 0
for _, v := range nums {
total += v
}
return total
}
func main() {
points := []int{5, 10, 15}
fmt.Println(addAll(points...))
}
|
Variadic functions can be invoked with a slice of arguments as well. |
What does the following code print? func plusSeven(num int) int {
plusFive := func(num int) int {
return num + 5
}
return plusFive(num) + 2
}
func main() {
fmt.Println(plusSeven(20))
}
|
The |
What does the following code print? func factorial(x uint) uint {
if x == 0 {
return 1
}
return x * factorial(x-1)
}
func main() {
fmt.Println(factorial(5))
}
|
Recursive functions are invoked in the function definition itself. |