0
0
Goprogramming~30 mins

Nested structs in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Nested structs
📖 Scenario: You are creating a simple program to store information about a book and its author. The author has a name and an age. The book has a title and an author.
🎯 Goal: You will build a Go program that uses nested structs to represent a book and its author, then print the book's title and the author's name.
📋 What You'll Learn
Create a struct called Author with fields Name string and Age int.
Create a struct called Book with fields Title string and Author Author.
Create a variable myBook of type Book with title "Go Programming" and author name "Alice" aged 30.
Print the book's title and the author's name exactly as shown.
💡 Why This Matters
🌍 Real World
Nested structs are useful to model real-world objects that have parts or details inside them, like a book having an author.
💼 Career
Understanding nested structs is important for Go developers working on data modeling, APIs, and complex data structures.
Progress0 / 4 steps
1
Define the Author struct
Write a struct called Author with two fields: Name of type string and Age of type int.
Go
Hint

Use type Author struct {} and add the fields inside the braces.

2
Define the Book struct with nested Author
Write a struct called Book with two fields: Title of type string and Author of type Author (the struct you defined earlier).
Go
Hint

Use type Book struct { Title string; Author Author } to nest the Author struct inside Book.

3
Create a variable myBook with nested data
Inside main(), create a variable called myBook of type Book. Set its Title to "Go Programming" and its Author to an Author struct with Name "Alice" and Age 30.
Go
Hint

Use composite literals to set nested struct fields, like myBook := Book{ Title: "Go Programming", Author: Author{Name: "Alice", Age: 30} }.

4
Print the book title and author name
Add a fmt.Println statement inside main() to print the book's title and the author's name in this exact format: "Title: Go Programming, Author: Alice". Remember to import the fmt package.
Go
Hint

Use fmt.Println("Title: ", myBook.Title, ", Author: ", myBook.Author.Name) to print the values.