0
0
Goprogramming~30 mins

Passing values vs pointers in Go - Hands-On Comparison

Choose your learning style9 modes available
Passing values vs pointers
📖 Scenario: Imagine you have a simple program that manages a person's age. You want to understand how changing the age inside a function affects the original age variable. This will help you learn the difference between passing values and passing pointers in Go.
🎯 Goal: You will create a program that shows how passing a value to a function does not change the original variable, but passing a pointer to a function allows you to change the original variable.
📋 What You'll Learn
Create a variable age with the value 30
Create a function increaseAgeValue that takes an int parameter and increases it by 1
Create a function increaseAgePointer that takes a pointer to an int and increases the value it points to by 1
Call both functions with the age variable and observe the difference
Print the value of age after each function call
💡 Why This Matters
🌍 Real World
Understanding passing by value and by pointer helps when writing programs that manage data efficiently, like updating user profiles or handling large data structures.
💼 Career
Many Go programming jobs require knowledge of pointers to write efficient and correct code, especially in system programming, backend services, and performance-critical applications.
Progress0 / 4 steps
1
Create the initial variable
Create a variable called age and set it to 30.
Go
Hint

Use age := 30 to create the variable.

2
Create the functions to increase age
Create two functions: increaseAgeValue that takes an int parameter called a and increases it by 1, and increaseAgePointer that takes a pointer to an int called a and increases the value it points to by 1.
Go
Hint

Remember, to change the original variable, use a pointer parameter and dereference it with *.

3
Call the functions with the variable
Inside main, call increaseAgeValue with age, then call increaseAgePointer with the address of age using &age.
Go
Hint

Call increaseAgeValue(age) and increaseAgePointer(&age) inside main.

4
Print the value of age after each function call
Add fmt.Println(age) after calling increaseAgeValue(age) and again after calling increaseAgePointer(&age) to show how the value changes.
Go
Hint

Use fmt.Println(age) after each function call to see the difference.