0
0
Goprogramming~15 mins

Why structs are used in Go - See It in Action

Choose your learning style9 modes available
Why structs are used
📖 Scenario: Imagine you want to keep information about books in a library. Each book has a title, an author, and a number of pages. You want to keep all this information together in one place.
🎯 Goal: You will create a struct in Go to group related information about a book. Then you will create a book using this struct, and finally print the book details.
📋 What You'll Learn
Create a struct named Book with fields Title (string), Author (string), and Pages (int).
Create a variable named myBook of type Book with the values: Title = "Go Programming", Author = "Alice", Pages = 300.
Print the details of myBook in a readable format.
💡 Why This Matters
🌍 Real World
Structs are used to model real-world objects with multiple properties, like books, people, or products.
💼 Career
Understanding structs is essential for Go programming jobs, as they are the foundation for organizing data and building applications.
Progress0 / 4 steps
1
Create the Book struct
Create a struct named Book with three fields: Title of type string, Author of type string, and Pages of type int.
Go
Hint

Use the type keyword to define a struct. Inside curly braces, list the fields with their types.

2
Create a Book variable
Inside the main function, create a variable named myBook of type Book and assign it the values: Title = "Go Programming", Author = "Alice", and Pages = 300.
Go
Hint

Use the struct literal syntax with field names to assign values.

3
Print the Book details
Inside the main function, after creating myBook, use fmt.Println to print the myBook variable.
Go
Hint

Remember to import the fmt package to use fmt.Println.

4
Print Book details in a friendly format
Replace the previous print statement with a fmt.Printf statement that prints: "Title: Go Programming, Author: Alice, Pages: 300" using the fields of myBook.
Go
Hint

Use fmt.Printf with %s for strings and %d for integers.