0
0
Goprogramming~15 mins

Creating struct values in Go - Try It Yourself

Choose your learning style9 modes available
Creating struct values
📖 Scenario: You are building a simple program to store information about a book in a library system.
🎯 Goal: Create a struct to represent a book and then create a value of that struct with specific details.
📋 What You'll Learn
Define a struct type named Book with fields Title (string), Author (string), and Year (int).
Create a variable named myBook of type Book with the exact values: Title = "The Go Programming Language", Author = "Alan A. A. Donovan", Year = 2015.
Print the myBook variable to display its contents.
💡 Why This Matters
🌍 Real World
Structs are used to group related data together, like storing information about books, users, or products in real applications.
💼 Career
Understanding structs is essential for Go programming jobs, as they are the foundation for creating complex data models.
Progress0 / 4 steps
1
Define the Book struct
Define a struct type called Book with three fields: Title of type string, Author of type string, and Year of type int.
Go
Hint

Use the type keyword to define a struct. Each field has a name and a type.

2
Create a Book value
Inside the main function, create a variable named myBook of type Book and assign it the values: Title = "The Go Programming Language", Author = "Alan A. A. Donovan", and Year = 2015.
Go
Hint

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

3
Print the Book value
Add a fmt.Println statement inside main to print the myBook variable.
Go
Hint

Use fmt.Println to display the struct value.

4
Run and see the output
Run the program and observe the printed output showing the myBook struct with its field values.
Go
Hint

The output should show the struct fields and their values inside curly braces.