0
0
Goprogramming~30 mins

Common pointer use cases in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Common pointer use cases
📖 Scenario: You are learning how pointers work in Go. Pointers let you directly change values stored in memory. This is useful when you want to update data inside functions or share data efficiently.
🎯 Goal: Build a simple Go program that uses pointers to update a variable's value, swap two numbers, and modify a struct field.
📋 What You'll Learn
Create an integer variable and a pointer to it
Create a function that uses a pointer to update an integer value
Create a function that swaps two integers using pointers
Create a struct and a function that modifies its field using a pointer
💡 Why This Matters
🌍 Real World
Pointers are used in Go to efficiently update data, manage memory, and work with complex data structures like linked lists or trees.
💼 Career
Understanding pointers is important for Go developers working on performance-critical applications, system programming, or backend services.
Progress0 / 4 steps
1
Create an integer variable and a pointer to it
Create an integer variable called num with value 10. Then create a pointer variable called ptr that points to num.
Go
Hint

Use & to get the address of a variable.

2
Create a function to update an integer value using a pointer
Add a function called updateValue that takes a pointer to an integer *int and sets the value it points to 20. Call updateValue in main passing ptr.
Go
Hint

Use *p = 20 to change the value at the pointer.

3
Create a function to swap two integers using pointers
Add a function called swap that takes two pointers to integers *int and swaps the values they point to. In main, create two integers a = 5 and b = 10, then call swap passing pointers to a and b.
Go
Hint

Use a temporary variable to swap values pointed by the pointers.

4
Create a struct and modify its field using a pointer
Define a struct type called Person with a field age of type int. Create a function called increaseAge that takes a pointer to Person and increases the age by 1. In main, create a Person variable with age = 30, then call increaseAge passing its pointer. Finally, print the updated age using fmt.Println.
Go
Hint

Use p.age += 1 to increase the age field through the pointer.