Tutorials Logic, IN info@tutorialslogic.com

Golang Pointers: Addresses, Dereferencing and Pointer Receivers

Golang Pointers

A Go pointer stores the memory address of a value. Pointers let functions modify existing values, avoid copying large structs, represent optional references, and define methods that mutate receiver state.

Go pointers are simpler than C pointers because Go does not allow pointer arithmetic in normal code. You use `&` to take an address and `*` to dereference a pointer. A pointer can also be `nil`, so nil checks are important before dereferencing uncertain values.

Golang is expanded here with a practical explanation, multiple examples, and beginner-focused checks so the idea is easier to learn from this page alone.

Read the concept first, then trace the example line by line. The important habit is to connect the rule to visible behavior instead of memorizing only the name.

Address and Dereference

The `&` operator gets the address of a variable. The `*` operator reads or writes the value at that address. If two variables point to the same value, a change through one pointer affects the original value.

  • `&value` means address of value.
  • `*ptr` means value stored at the pointer address.
  • A nil pointer points to nothing and cannot be safely dereferenced.
  • Use pointers when a function needs to mutate a caller-owned value.

Modify Through Pointer

Modify Through Pointer
package main

import "fmt"

func applyDiscount(price *int, amount int) {
	*price = *price - amount
}

func main() {
	total := 1000
	applyDiscount(&total, 150)
	fmt.Println(total) // 850
}

Pointer Receivers

Methods can use value receivers or pointer receivers. Use a pointer receiver when the method should modify the struct or when copying the struct would be expensive.

  • Value receivers receive a copy of the struct.
  • Pointer receivers can update the original struct.
  • Keep receiver style consistent for a type when possible.
  • Maps, slices, and channels already contain reference-like internals, but structs often need pointer receivers for mutation.

Pointer Receiver Method

Pointer Receiver Method
type Counter struct {
	Value int
}

func (c *Counter) Increment() {
	c.Value++
}

func main() {
	counter := Counter{}
	counter.Increment()
	fmt.Println(counter.Value) // 1
}

When Not to Use Pointers

Pointers are useful, but unnecessary pointers can make code harder to read. Small immutable values such as ints, booleans, and short structs can often be passed by value.

  • Do not use pointers only to look advanced.
  • Avoid returning pointers to shared mutable state unless ownership is clear.
  • Check nil before dereferencing optional pointer values.
  • Prefer clear data ownership over clever pointer passing.

Detailed Explanation of Golang

Golang becomes much easier when you separate the concept from the tool syntax. First identify the problem being solved, then identify the data or resource being changed, and finally identify the proof that the change worked.

In Golang, this topic should be studied through explicit types, readable control flow, error returns, package boundaries, and small tests. Those points explain not only how to use the feature, but also why it fails when the wrong assumption is made.

The previous audit note was: under 650 content words . This expanded section adds a fuller explanation, concrete examples, and practice guidance so the page can stand on its own for beginners.

A good way to learn this page is to read the normal path once, run or trace the example, then intentionally change one input to observe the different result. That one change teaches more than memorizing several definitions.

  • Write the goal of Golang before touching code or configuration.
  • Identify the normal case, edge case, and failure case.
  • Trace what changes before and after the operation.
  • Use a command, output, compiler message, log, metric, or table to verify the result.
  • Record the mistake that would confuse a beginner and the exact fix.

Beginner-Friendly Walkthrough for Golang

Start with a tiny project scenario. For example, imagine one user action, one request, one resource, one function call, or one batch of data. Keep the scenario small enough that every step can be explained without skipping details.

Next, describe the movement of information. Where does the input start? Which rule or component handles it? What result should appear? If the result is wrong, where would you inspect first?

Finally, compare two outcomes. The correct outcome proves that you understand the main rule. The incorrect outcome teaches the symptom, which is what you will recognize later during debugging or interviews.

  • Normal path: valid input produces the expected result.
  • Boundary path: the smallest, largest, empty, or unusual input still behaves predictably.
  • Error path: a realistic mistake creates a visible symptom.
  • Fix path: one focused correction removes the symptom without changing unrelated code.

Nil Pointer Guard

Nil Pointer Guard
func printName(name *string) {
	if name == nil {
		fmt.Println("name is missing")
		return
	}
	fmt.Println(*name)
}

Golang complete Go practice example

Golang complete Go practice example
package main

import "fmt"

func explainGolang(values []int) {
    for index, value := range values {
        fmt.Printf("Golang step %d has value %d\n", index+1, value)
    }
}

func main() {
    explainGolang([]int{1, 3, 5})
}

Golang Go edge-case example

Golang Go edge-case example
package main

import "errors"

func validateGolang(items []string) error {
    if len(items) == 0 {
        return errors.New("Golang: at least one item is required")
    }
    return nil
}
Key Takeaways
  • Use `&` to take an address and `*` to dereference.
  • Use pointer receivers for mutating methods.
  • Check nil before dereferencing uncertain pointers.
  • Avoid pointers when simple value passing is clearer.
  • Explain the purpose of Golang in your own words.
  • Run or trace a small Golang example for Golang.
  • Test a normal case, a boundary case, and a broken case.
  • Verify the result with visible output, logs, metrics, compiler feedback, or a table.
  • Summarize the common mistake and the correction.
Common Mistakes to Avoid
WRONG Dereference a nil pointer.
RIGHT Check for nil first when a pointer may be absent.
Nil pointer dereference causes a runtime panic.
WRONG Use value receiver for a method that should mutate a struct.
RIGHT Use pointer receiver for mutation.
Value receivers modify a copy.
WRONG Learning Golang only as a term.
RIGHT Learn it through a working example, a boundary case, and a failure case.
Concept plus behavior is easier to remember than definition alone.
WRONG Skipping verification.
RIGHT Always check output, state, logs, metrics, query results, or compiler feedback.
Verification turns confidence into evidence.
WRONG Changing many things at once while debugging.
RIGHT Change one setting, input, or line, then inspect the result.
Small changes reveal the real cause.

Practice Tasks

  • Write a function that doubles an integer through a pointer.
  • Create a `Cart` struct with a pointer receiver method that adds an item.
  • Write a safe function that accepts `*User` and handles nil input.
  • Create a small demo that shows Golang clearly.
  • Add one edge case and write the expected result before running it.
  • Break the demo intentionally and document the error symptom.
  • Fix the broken version and explain why the fix works.

Frequently Asked Questions

Not in normal safe Go code. Go pointers reference values but do not support C-style arithmetic.

No. Use pointer receivers for mutation, large structs, or consistency when some methods require pointers.

Start with one tiny example, trace every step, then compare it with a broken version.

Verify the visible result: output, state, log entry, metric, query result, compiler feedback, or rendered behavior.

It often combines vocabulary with behavior. The confusion drops when you trace the input, rule, result, and failure path.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.