0
0
Goprogramming~15 mins

Method call behavior in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Method call behavior
📖 Scenario: Imagine you have a simple program that manages a counter. You want to understand how calling methods on a value type and a pointer type affects the data.
🎯 Goal: You will create a Counter struct, add methods to increase the count, and observe how method calls behave differently when using a value receiver versus a pointer receiver.
📋 What You'll Learn
Create a struct called Counter with a field count of type int
Create a method IncrementValue with a value receiver that increases count by 1
Create a method IncrementPointer with a pointer receiver that increases count by 1
Create a main function to test calling both methods on a Counter value and pointer
Print the count after each method call to observe the behavior
💡 Why This Matters
🌍 Real World
Understanding method call behavior is important when working with structs in Go, especially when you want to modify data inside methods or keep data immutable.
💼 Career
Many Go jobs require writing clean and efficient code with structs and methods. Knowing when to use pointer receivers versus value receivers helps avoid bugs and improves performance.
Progress0 / 4 steps
1
Create the Counter struct
Create a struct called Counter with a field count of type int.
Go
Hint

Use the type keyword to define a struct named Counter with one field count of type int.

2
Add methods IncrementValue and IncrementPointer
Add two methods to Counter: IncrementValue with a value receiver that adds 1 to count, and IncrementPointer with a pointer receiver that adds 1 to count.
Go
Hint

Define IncrementValue with a value receiver c Counter and increase c.count by 1. Define IncrementPointer with a pointer receiver c *Counter and increase c.count by 1.

3
Create main function and call methods
Create a main function. Inside it, create a variable c of type Counter. Call IncrementValue on c, then call IncrementPointer on the address of c. After each call, print c.count using fmt.Println.
Go
Hint

Inside main, create c as Counter{}. Call c.IncrementValue(), print c.count, then call c.IncrementPointer() and print c.count again.

4
Run and observe the output
Run the program and observe the output. It should print the value of c.count after each method call. Write a fmt.Println statement to print the final value of c.count after both method calls.
Go
Hint

Notice that calling IncrementValue does not change c.count because it works on a copy. Calling IncrementPointer changes c.count because it works on the original.