How to Use Pointer with Function in Go: Simple Guide
In Go, you use a
pointer with a function by passing the variable's memory address using & and receiving it as a pointer parameter with *Type. This allows the function to modify the original variable directly.Syntax
To use a pointer with a function in Go, define the function parameter as a pointer type using *Type. When calling the function, pass the address of the variable using &variable.
func functionName(param *Type): Function receives a pointer.functionName(&variable): Pass variable's address.- Inside the function, use
*paramto access or modify the original value.
go
package main import "fmt" func modifyValue(num *int) { *num = *num + 10 } func main() { value := 5 modifyValue(&value) fmt.Println(value) // Output: 15 }
Example
This example shows how a function can change the original variable by receiving its pointer. The function increment adds 1 to the value pointed to by the pointer.
go
package main import "fmt" func increment(num *int) { *num = *num + 1 } func main() { count := 10 fmt.Println("Before:", count) increment(&count) fmt.Println("After:", count) }
Output
Before: 10
After: 11
Common Pitfalls
Common mistakes when using pointers with functions include:
- Passing the variable directly instead of its address, so the function gets a copy, not a pointer.
- Not using
*to dereference the pointer inside the function, so changes don't affect the original variable. - Confusing pointer types and values, leading to compilation errors.
go
package main import "fmt" // Wrong: parameter is int, not pointer func wrongIncrement(num int) { num = num + 1 } // Correct: parameter is pointer to int func correctIncrement(num *int) { *num = *num + 1 } func main() { value := 5 wrongIncrement(value) fmt.Println("After wrongIncrement:", value) // Still 5 correctIncrement(&value) fmt.Println("After correctIncrement:", value) // Now 6 }
Output
After wrongIncrement: 5
After correctIncrement: 6
Quick Reference
| Concept | Syntax | Description |
|---|---|---|
| Pointer Parameter | func f(p *int) | Function receives pointer to int |
| Pass Address | f(&x) | Pass variable's address to function |
| Dereference Pointer | *p | Access or modify value pointed by p |
| Modify Original | *p = newValue | Change original variable's value |
Key Takeaways
Pass a variable's address using & to send a pointer to a function.
Declare function parameters as pointers using *Type to receive addresses.
Use * to access or change the value the pointer points to inside the function.
Passing pointers lets functions modify the original variables directly.
Avoid passing values when you want to change the original variable.