0
0
Goprogramming~20 mins

Defining structs in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Struct Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of struct field access
What is the output of this Go program?
Go
package main
import "fmt"
type Person struct {
  Name string
  Age  int
}
func main() {
  p := Person{Name: "Alice", Age: 30}
  fmt.Println(p.Name)
}
AAlice
B30
CPerson{Name: "Alice", Age: 30}
DCompilation error
Attempts:
2 left
💡 Hint
Look at which field is printed with fmt.Println.
Predict Output
intermediate
2:00remaining
Output when struct fields are uninitialized
What is the output of this Go program?
Go
package main
import "fmt"
type Point struct {
  X int
  Y int
}
func main() {
  var p Point
  fmt.Println(p.X, p.Y)
}
Anil nil
BCompilation error: missing initialization
C0 0
DRandom values
Attempts:
2 left
💡 Hint
Uninitialized int fields default to zero.
🔧 Debug
advanced
2:00remaining
Identify the error in struct initialization
What error does this Go code produce?
Go
package main
import "fmt"
type Car struct {
  Brand string
  Year  int
}
func main() {
  c := Car{Brand: "Toyota", Year: 2020}
  fmt.Println(c)
}
ASyntax error: mixed field names and values
BCompilation error: missing field Year
CRuntime panic: invalid type conversion
DNo error, prints {Toyota 2020}
Attempts:
2 left
💡 Hint
Check how struct fields are initialized with names and values.
Predict Output
advanced
2:00remaining
Output of nested structs
What is the output of this Go program?
Go
package main
import "fmt"
type Address struct {
  City  string
  State string
}
type User struct {
  Name    string
  Address Address
}
func main() {
  u := User{Name: "Bob", Address: Address{City: "NYC", State: "NY"}}
  fmt.Println(u.Address.City)
}
ANY
BNYC
C{City: NYC, State: NY}
DCompilation error
Attempts:
2 left
💡 Hint
Look at which nested field is printed.
🧠 Conceptual
expert
2:00remaining
Number of fields in an anonymous struct
How many fields does this struct have?
Go
var s = struct {
  A int
  B string
  C struct {
    D float64
    E bool
  }
}{}
A3
B5
C2
D4
Attempts:
2 left
💡 Hint
Count only the top-level fields of the struct.