0
0
Goprogramming~15 mins

Pointer behavior in functions in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Pointer behavior in functions
📖 Scenario: Imagine you have a number and you want to change its value inside a function. In Go, you can use pointers to do this. Pointers let you share the address of a variable so the function can change the original value.
🎯 Goal: You will create a Go program that shows how passing a pointer to a function allows the function to change the original variable's value.
📋 What You'll Learn
Create an integer variable called num with the value 10.
Create a function called changeValue that takes a pointer to an integer.
Inside changeValue, change the value pointed to by the pointer to 20.
Call changeValue passing the address of num.
Print the value of num after calling the function.
💡 Why This Matters
🌍 Real World
Pointers are used in Go to efficiently change data without copying it. This is common in programs that manage memory or work with large data.
💼 Career
Understanding pointers is important for Go developers, especially when working on performance-critical applications or systems programming.
Progress0 / 4 steps
1
Create the initial variable
Create an integer variable called num and set it to 10.
Go
Hint

Use num := 10 to create the variable.

2
Create the function with a pointer parameter
Create a function called changeValue that takes a pointer to an integer named p. Inside the function, set the value pointed to by p to 20.
Go
Hint

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

3
Call the function with the pointer
Inside main, call the function changeValue passing the address of num using &num.
Go
Hint

Use changeValue(&num) to pass the pointer.

4
Print the changed value
Add a fmt.Println statement to print the value of num after calling changeValue.
Go
Hint

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