0
0
Goprogramming~20 mins

Zero values in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Go Zero Values Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
Output of uninitialized variables
What is the output of this Go program?
Go
package main
import "fmt"
func main() {
    var a int
    var b string
    var c bool
    fmt.Printf("%d %q %t", a, b, c)
}
A0 "" false
B0 "0" false
C0 "nil" false
D0 "" true
Attempts:
2 left
๐Ÿ’ก Hint
Think about what Go assigns to variables when you don't set them.
โ“ Predict Output
intermediate
2:00remaining
Zero value of a slice
What will this Go program print?
Go
package main
import "fmt"
func main() {
    var s []int
    fmt.Println(s == nil)
    fmt.Println(len(s))
}
A
false
0
B
true
-1
C
true
0
D
false
-1
Attempts:
2 left
๐Ÿ’ก Hint
Slices have a zero value of nil and length zero.
โ“ Predict Output
advanced
2:00remaining
Zero value of a map and its behavior
What is the output of this Go program?
Go
package main
import "fmt"
func main() {
    var m map[string]int
    fmt.Println(m == nil)
    fmt.Println(m["key"])
    m["key"] = 10
}
A
false
0
panic: assignment to entry in nil map
B
false
0
no panic
C
true
0
no panic
D
true
0
panic: assignment to entry in nil map
Attempts:
2 left
๐Ÿ’ก Hint
Maps have zero value nil, reading from nil map is allowed, writing causes panic.
โ“ Predict Output
advanced
2:00remaining
Zero value of a struct with embedded fields
What will this Go program print?
Go
package main
import "fmt"
type Inner struct {
    X int
}
type Outer struct {
    Inner
    Y string
}
func main() {
    var o Outer
    fmt.Printf("%d %q", o.X, o.Y)
}
A0 ""
B0 "nil"
C0 "0"
Dpanic at runtime
Attempts:
2 left
๐Ÿ’ก Hint
Embedded structs get zero values too.
โ“ Predict Output
expert
2:00remaining
Zero value of interface and type assertion
What is the output of this Go program?
Go
package main
import "fmt"
func main() {
    var i interface{}
    fmt.Println(i == nil)
    v, ok := i.(int)
    fmt.Println(v, ok)
}
A
false
0 false
B
true
0 false
C
true
0 true
D
false
0 true
Attempts:
2 left
๐Ÿ’ก Hint
An uninitialized interface is nil; type assertion fails safely.