0
0
Goprogramming~15 mins

Why pointers are needed in Go - See It in Action

Choose your learning style9 modes available
Why pointers are needed
📖 Scenario: Imagine you have a list of boxes, each with a number inside. You want to change the number inside a box without making a copy of the box. This is like using pointers in Go.
🎯 Goal: You will create a simple Go program that shows how pointers let you change the original value of a variable by using its address.
📋 What You'll Learn
Create an integer variable called number with the value 10
Create a pointer variable called ptr that points to number
Change the value of number through the pointer ptr to 20
Print the value of number to show it has changed
💡 Why This Matters
🌍 Real World
Pointers are used in real programs to efficiently update data without copying it, like changing settings or updating large data structures.
💼 Career
Understanding pointers is important for Go developers to write efficient and clear code, especially when working with functions, data structures, and system programming.
Progress0 / 4 steps
1
Create an integer variable
Create an integer variable called number and set it to 10.
Go
Hint

Use := to create and set the variable in one line.

2
Create a pointer to the variable
Create a pointer variable called ptr that stores the address of number using the & operator.
Go
Hint

Use &number to get the address of the variable number.

3
Change the value using the pointer
Use the pointer ptr to change the value of number to 20. Use the * operator to access the value at the pointer.
Go
Hint

Use *ptr = 20 to set the value at the address stored in ptr.

4
Print the changed value
Print the value of number using fmt.Println(number) to show it has changed to 20. Remember to import fmt.
Go
Hint

Use fmt.Println(number) to print the value.