0
0
Goprogramming~20 mins

Nested structs in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Nested Structs Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of nested struct field access
What is the output of this Go program?
Go
package main
import "fmt"
type Address struct {
    City string
    Zip  int
}
type Person struct {
    Name    string
    Address Address
}
func main() {
    p := Person{Name: "Alice", Address: Address{City: "Paris", Zip: 75000}}
    fmt.Println(p.Address.City)
}
A75000
BAddress{City: "Paris", Zip: 75000}
CAlice
DParis
Attempts:
2 left
💡 Hint
Look at how nested structs are accessed using dot notation.
Predict Output
intermediate
2:00remaining
Output of nested struct pointer access
What will this Go program print?
Go
package main
import "fmt"
type Engine struct {
    Horsepower int
}
type Car struct {
    Model  string
    Engine *Engine
}
func main() {
    e := Engine{Horsepower: 300}
    c := Car{Model: "Mustang", Engine: &e}
    fmt.Println(c.Engine.Horsepower)
}
AMustang
Bnil
C300
D0
Attempts:
2 left
💡 Hint
Remember to dereference pointers automatically with dot notation.
🔧 Debug
advanced
2:00remaining
Identify the compilation error in nested struct initialization
This Go code does not compile. What is the cause of the error?
Go
package main
import "fmt"
type Point struct {
    X, Y int
}
type Rectangle struct {
    TopLeft, BottomRight Point
}
func main() {
    r := Rectangle{TopLeft: Point{X: 0, Y: 10}, BottomRight: Point{X: 5, Y: 0}}
    fmt.Println(r)
}
AMissing type name in nested struct literals
BCannot use composite literals inside struct initialization
CFields TopLeft and BottomRight are unexported
Dfmt.Println cannot print structs
Attempts:
2 left
💡 Hint
Check how nested structs are initialized in Go.
Predict Output
advanced
2:00remaining
Output of embedded struct field promotion
What does this Go program print?
Go
package main
import "fmt"
type Contact struct {
    Email string
}
type Employee struct {
    Name    string
    Contact
}
func main() {
    e := Employee{Name: "Bob", Contact: Contact{Email: "bob@example.com"}}
    fmt.Println(e.Email)
}
AName field value: Bob
Bbob@example.com
CCompilation error: ambiguous field
DContact{Email: "bob@example.com"}
Attempts:
2 left
💡 Hint
Embedded structs promote their fields to the outer struct.
🧠 Conceptual
expert
2:00remaining
Number of fields in nested and embedded structs
Given these struct definitions, how many fields does variable 'd' of type Developer have?
Go
type Address struct {
    City string
    Zip  int
}
type Contact struct {
    Email string
    Phone string
}
type Developer struct {
    Name    string
    Address
    Contact
}
A5
B3
C4
D6
Attempts:
2 left
💡 Hint
Count all fields including embedded struct fields promoted to Developer.