0
0
GoHow-ToBeginner · 3 min read

How to Create Pointer in Go: Syntax and Examples

In Go, you create a pointer by using the & operator to get the memory address of a variable. The pointer variable stores this address and is declared with an asterisk * before its type, like var p *int.
📐

Syntax

To create a pointer in Go, declare a variable with an asterisk * before the type to indicate it holds a memory address. Use the & operator to get the address of a variable.

  • Declaration: var p *int means p is a pointer to an integer.
  • Address-of operator: &x gets the memory address of variable x.
  • Dereferencing: *p accesses the value stored at the address p points to.
go
var p *int
var x int = 10
p = &x
// p now holds the address of x
// *p accesses the value 10
💻

Example

This example shows how to create a pointer to an integer, change the value through the pointer, and print both the original and changed values.

go
package main

import "fmt"

func main() {
    x := 42
    p := &x // p points to x

    fmt.Println("Original value of x:", x)
    fmt.Println("Pointer p holds address:", p)
    fmt.Println("Value via pointer *p:", *p)

    *p = 100 // change value of x through pointer

    fmt.Println("New value of x after *p = 100:", x)
}
Output
Original value of x: 42 Pointer p holds address: 0xc0000140b8 Value via pointer *p: 42 New value of x after *p = 100: 100
⚠️

Common Pitfalls

Beginners often confuse pointers with values or forget to use the & operator to get an address. Another mistake is trying to dereference a nil pointer, which causes a runtime error.

Always initialize pointers before dereferencing.

go
package main

import "fmt"

func main() {
    var p *int
    // fmt.Println(*p) // This will cause a panic: dereferencing nil pointer

    x := 5
    p = &x // Correct: assign address before dereferencing
    fmt.Println(*p) // prints 5
}
Output
5
📊

Quick Reference

ConceptSyntaxDescription
Pointer declarationvar p *intDeclares p as a pointer to an int
Get address&xGets the memory address of variable x
Dereference pointer*pAccesses or changes the value at the address p points to
Assign pointerp = &xAssigns the address of x to pointer p
Nil pointervar p *intPointer with no address assigned (nil)

Key Takeaways

Use & to get the address of a variable and * to declare or dereference a pointer.
Pointers store memory addresses, not the actual values.
Always initialize pointers before dereferencing to avoid runtime errors.
Changing a value through a pointer changes the original variable.
Nil pointers cause errors if dereferenced; always check or initialize.