DEV Community

Cover image for Pointers in Go Programming Language
Hazar
Hazar

Posted on

Pointers in Go Programming Language

Understanding Pointers in Programming

Pointers are one of the most fundamental and powerful concepts in programming. Whether you're a beginner or an experienced coder, mastering pointers can take your skills to the next level. In this article, we will explore what pointers are, why they are essential, and how to use them effectively in your code.

What Are Pointers?

Imagine you have a magical tool that can directly access and manipulate the memory of your computer. This is what pointers do! Pointers are variables that store memory addresses instead of actual data values. When you create a pointer to a variable, you are essentially storing the location of that variable in memory.

How to Use Pointers

Declaration and Initialization

Declaration

Declaring a pointer in Go is simple. You use the * operator to specify that you are creating a pointer. Here's how to declare a pointer to an integer:

var p *int
Enter fullscreen mode Exit fullscreen mode
Initialization

To initialize the pointer, you assign it the address of a variable using the & operator:

x := 10
p = &x
Enter fullscreen mode Exit fullscreen mode

Here's an example of using & in a canvas:
pointers canvas

Practical Example

Let’s walk through a practical example to understand pointers better.

Step 1: Declare an Integer Variable
x := 10
fmt.Println("Value of x: ", x)
fmt.Println("Address of x: ", &x)
Enter fullscreen mode Exit fullscreen mode

Output:

Value of x: 10
Address of x: 0xc000012150
Enter fullscreen mode Exit fullscreen mode
Step 2: Declare a Pointer to an Integer
var p *int
Enter fullscreen mode Exit fullscreen mode
Step 3: Initialize the Pointer with the Address of x
p = &x
fmt.Println("Pointer p: ", p)
fmt.Println("Value at pointer p: ", *p)
Enter fullscreen mode Exit fullscreen mode

Output:

Pointer p: 0xc000012150
Value at pointer p: 10
Enter fullscreen mode Exit fullscreen mode
Step 4: Modify the Value at the Address the Pointer is Pointing To
*p = 20
fmt.Println("Modified value of x: ", x)
Enter fullscreen mode Exit fullscreen mode

Output:

Modified value of x: 20
Enter fullscreen mode Exit fullscreen mode

Why Pointers?

Why should you care about pointers? Pointers are crucial for several reasons:

  1. Memory Efficiency: Pointers allow you to manage memory directly, which can lead to more efficient programs.
  2. Data Manipulation: Pointers enable you to manipulate data directly in memory, which can be faster than copying data around.
  3. Dynamic Memory Allocation: Pointers are essential for dynamic memory allocation, which is crucial for creating flexible and scalable programs.

Real-World Example: Using Pointers for Efficiency

Consider the following example where we update a user session's expiration time:

package main

import (
    "fmt"
    "time"
)

type UserSession struct {
    UserID          int
    Username        string
    ExpirationTime  time.Time
}

func updateSessionExpiration(session *UserSession) {
    session.ExpirationTime = session.ExpirationTime.Add(1 * time.Hour)
}

func updateSessionExpirationWithoutPointer(session UserSession) UserSession {
    session.ExpirationTime = session.ExpirationTime.Add(1 * time.Hour)
    return session
}
Enter fullscreen mode Exit fullscreen mode

In this example, updateSessionExpiration modifies the original session using a pointer, while updateSessionExpirationWithoutPointer takes a session by value (creating a copy) and returns a new session after modification.

When we modify the original session using a pointer, the changes made inside the function affect the original session object. However, when we pass the session by value and modify it inside the function, a copy of the session is created, and the changes only affect this copy. The original session remains unchanged.

Conclusion

Pointers might seem intimidating at first, but they are an incredibly powerful tool in programming. Understanding and mastering pointers will enable you to write more efficient, flexible, and powerful code. So dive in, experiment with pointers, and unlock a new level of programming expertise!

Top comments (3)

Collapse
 
efpage profile image
Eckehard • Edited

Sorry, but pointers are one of the most outdated features in programming languages. They are a fundamental element of machine programming and where introduced in C as a way to reference a variable. But they are a reason for most of the security issues of C.

Most moden programming languages skipped this concept and know ways to reference a variable wihtout the security issues. It´s very hard to understand why Go adopted this archaic concept.

Collapse
 
hazar profile image
Hazar

Thanks for your comment! You're right that pointers can cause security issues in languages like C. Go includes pointers to improve performance and control, but it also restricts risky operations and has automatic memory management to keep things safe. This makes Go both efficient and safer than traditional pointer use in C.
Here are some resources:
Reddit: When to use pointers?
Pointer arithmetic in Go

Collapse
 
efpage profile image
Eckehard • Edited

It´s more the concept that is outdated. It forces the programmer to think about a level of bare metal programming that could be better handeled by a computer than a human.

See this example:

var p *int
*p = 20
Enter fullscreen mode Exit fullscreen mode

As the pointer points to nowhere, this gives an error. Why do we allow these kind of silly errors to occur?

There are also some conceptual issues. Think about pointers from a this perspective: What is a Variable? Is a variable a value? No. A variable is a reference to a memory location, where a value is stored. So, basically, a variable is already a pointer. If you write something like this:

x := 10
p = &x
Enter fullscreen mode Exit fullscreen mode

Now you have two variables that point to the same memory location, which can cause a lot of trouble if you do not care. Unless you check the adress, you cannot know that p is somehow coupled to x.

Many languages do not use pointers as they do not need them. If you want to use the advantage of a pointer in C#, you just write this:

x = 10
myFunction(ref x)
Enter fullscreen mode Exit fullscreen mode

refs lets you pass the variable by reference without using pointers. This is enough to get all the merits of indirect adressing.