0
0
Goprogramming~20 mins

Why structs are used in Go - Challenge Your Understanding

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!
🧠 Conceptual
intermediate
1:00remaining
Purpose of structs in Go
Why do Go programmers use structs in their programs?
ATo perform mathematical calculations faster
BTo create loops that run multiple times
CTo replace functions with variables
DTo group related data together into a single unit
Attempts:
2 left
💡 Hint
Think about how you can organize information about a person or an object.
Predict Output
intermediate
1:30remaining
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: "Anna", Age: 30}
  fmt.Println(p.Name)
}
APerson{Name:"Anna", Age:30}
BAnna
C30
DCompilation error
Attempts:
2 left
💡 Hint
Look at which field is printed with fmt.Println.
Predict Output
advanced
1:30remaining
Structs and pointers output
What will this Go program print?
Go
package main
import "fmt"
type Point struct {
  X, Y int
}
func main() {
  p := Point{X: 5, Y: 10}
  q := &p
  q.X = 20
  fmt.Println(p.X, p.Y)
}
A20 10
B5 10
CCompilation error
D20 0
Attempts:
2 left
💡 Hint
Changing a field through a pointer affects the original struct.
🧠 Conceptual
advanced
1:00remaining
Why use structs instead of separate variables?
What is a key advantage of using structs over separate variables for related data?
AStructs automatically create user interfaces
BStructs run faster than separate variables
CStructs allow grouping related data, making code easier to read and maintain
DStructs prevent any changes to data once created
Attempts:
2 left
💡 Hint
Think about organizing information logically.
Predict Output
expert
2:00remaining
Struct embedding and field access output
What is the output of this Go program?
Go
package main
import "fmt"
type Animal struct {
  Name string
}
type Dog struct {
  Animal
  Breed string
}
func main() {
  d := Dog{Animal: Animal{Name: "Buddy"}, Breed: "Beagle"}
  fmt.Println(d.Name, d.Breed)
}
ABuddy Beagle
BAnimal Beagle
CBuddy Animal
DCompilation error
Attempts:
2 left
💡 Hint
Embedded structs let you access fields directly.