0
0
Goprogramming~30 mins

Value receivers in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Value Receivers in Go
📖 Scenario: Imagine you are creating a simple program to manage a book's information. You want to understand how changing a book's title inside a method affects the original book data.
🎯 Goal: You will create a Book struct and a method with a value receiver that tries to change the book's title. You will see if the original book's title changes or not.
📋 What You'll Learn
Create a Book struct with a title field of type string
Create a method ChangeTitle with a value receiver that changes the title field
Create a Book variable with an initial title
Call the ChangeTitle method on the Book variable
Print the book's title before and after calling ChangeTitle
💡 Why This Matters
🌍 Real World
Value receivers are used in Go when you want methods to work on copies of data, ensuring the original data stays unchanged. This is useful in many programs where data safety is important.
💼 Career
Understanding value vs pointer receivers is essential for Go developers to write efficient and bug-free code, especially when working with structs and methods.
Progress0 / 4 steps
1
Create the Book struct
Create a struct called Book with one field title of type string.
Go
Hint

Use the type keyword to define a struct named Book with a title field.

2
Create the ChangeTitle method with a value receiver
Create a method called ChangeTitle with a value receiver of type Book. Inside the method, set the title field to "New Title".
Go
Hint

Define a method with func (b Book) ChangeTitle() and change b.title inside it.

3
Create a Book variable and call ChangeTitle
Create a variable called myBook of type Book with the title "Original Title". Then call myBook.ChangeTitle().
Go
Hint

Create myBook with Book{title: "Original Title"} and call myBook.ChangeTitle().

4
Print the book title before and after calling ChangeTitle
Add fmt.Println statements to print myBook.title before and after calling myBook.ChangeTitle(). Import fmt package as needed.
Go
Hint

Use fmt.Println(myBook.title) before and after calling ChangeTitle() to see if the title changes.