0
0
Goprogramming~20 mins

Creating struct values in Go - Practice Exercises

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Go Struct Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of struct literal with field names
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)
}
A{Name: Alice, Age: 30}
B{Alice 30}
CPerson{Name: "Alice", Age: 30}
D{Name:Alice Age:30}
Attempts:
2 left
💡 Hint
Look at how fmt.Println prints structs by default.
Predict Output
intermediate
2:00remaining
Output of struct literal without field names
What is the output of this Go program?
Go
package main
import "fmt"
type Point struct {
    X int
    Y int
}
func main() {
    p := Point{10, 20}
    fmt.Println(p)
}
APoint{10, 20}
B{X=10, Y=20}
C{10 20}
D{X:10 Y:20}
Attempts:
2 left
💡 Hint
Struct literals can omit field names if values are in order.
Predict Output
advanced
2:00remaining
Output of nested struct values
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: "NY", State: "NY"}}
    fmt.Println(u)
}
AUser{Name: "Bob", Address: Address{City: "NY", State: "NY"}}
B{Name:Bob Address:{City:NY State:NY}}
C{Bob {City:NY State:NY}}
D{Bob {NY NY}}
Attempts:
2 left
💡 Hint
fmt.Println prints nested structs recursively without field names.
Predict Output
advanced
2:00remaining
Output of pointer to struct literal
What is the output of this Go program?
Go
package main
import "fmt"
type Car struct {
    Brand string
    Year  int
}
func main() {
    c := &Car{Brand: "Tesla", Year: 2022}
    fmt.Println(*c)
}
A{Tesla 2022}
B&{Tesla 2022}
C{Brand:Tesla Year:2022}
DCar{Brand: "Tesla", Year: 2022}
Attempts:
2 left
💡 Hint
Dereferencing pointer prints the struct value.
🧠 Conceptual
expert
3:00remaining
Number of fields in struct literal with embedded struct
Given the structs below, how many fields does the struct literal have when creating a value of type Employee?
Go
type Person struct {
    Name string
    Age  int
}
type Employee struct {
    Person
    ID int
}

// Creating value:
// e := Employee{Person{Name: "Eve", Age: 28}, 101}
A2 fields: Person and ID
B3 fields: Name, Age, and ID
C1 field: ID only
D4 fields: Person, Name, Age, and ID
Attempts:
2 left
💡 Hint
Embedded structs count as one field in the outer struct literal.