0
0
Goprogramming~15 mins

Accessing struct fields in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Accessing struct fields
📖 Scenario: You are creating a simple program to store information about a book in a library.
🎯 Goal: You will create a struct to hold book details, set up a book variable, and then access and print its fields.
📋 What You'll Learn
Create a struct type named Book with fields Title (string) and Pages (int).
Create a variable myBook of type Book with Title set to "Go Programming" and Pages set to 300.
Access the Title and Pages fields of myBook and store them in variables bookTitle and bookPages.
Print the values of bookTitle and bookPages.
💡 Why This Matters
🌍 Real World
Structs are used to group related data together, like storing information about books, people, or products in programs.
💼 Career
Understanding structs and how to access their fields is essential for Go programming jobs, especially when working with data models and APIs.
Progress0 / 4 steps
1
Create the Book struct
Create a struct type called Book with two fields: Title of type string and Pages of type int.
Go
Hint

Use type Book struct {} syntax to define the struct with the two fields inside.

2
Create a Book variable
Inside the main function, create a variable called myBook of type Book and set Title to "Go Programming" and Pages to 300.
Go
Hint

Use struct literal syntax: myBook := Book{Title: "Go Programming", Pages: 300}.

3
Access struct fields
Inside the main function, after creating myBook, create two variables: bookTitle and bookPages. Assign myBook.Title to bookTitle and myBook.Pages to bookPages.
Go
Hint

Use dot notation to access fields: myBook.Title and myBook.Pages.

4
Print the field values
Use fmt.Println to print the values of bookTitle and bookPages inside the main function.
Go
Hint

Use fmt.Println(bookTitle) and fmt.Println(bookPages) to print the values on separate lines.